Jsont 11252bb-dirty

Jsont is an OCaml library for declarative JSON data manipulation. It provides:

The descriptions are independent from the codec and can be used by third-party processors or codecs.

See the quick start.

Manuals

The following manuals are available.

The test directory in the repository of Jsont has a few more examples.

Library jsont

Library jsont.brr

This library depends on the brr package.

Quick start

Given JSON for task items encoded in JSON as follows:

let data =
{|
{ "task": "Make new release",
  "status": "todo",
  "tags": ["work", "softwre"] }
|}

First we can correct that typo in the "tags" list with:

let () =
  let p = Jsont.Path.(root |> mem "tags" |> nth 1) in
  let update = Jsont.(set_path string p "software") in
  let correct = Jsont_codec.recode_string ~layout:true update data in
  print_string (Result.get_ok correct)

Now to work with the data in OCaml without pain we can model it by:

module Status = struct
  type t = Todo | Done | Cancelled
  let assoc = ["todo", Todo; "done", Done; "cancelled", Cancelled ]
  let jsont = Jsont.enum ~kind:"Status" assoc
end

module Item = struct
  type t = { task : string; status : Status.t; tags : string list; }
  let make task status tags = { task; status; tags }
  let task i = i.task
  let status i = i.status
  let tags i = i.tags
  let jsont =
    Jsont.Obj.map ~kind:"Item" make
    |> Jsont.Obj.mem "task" Jsont.string ~enc:task
    |> Jsont.Obj.mem "status" Status.jsont ~enc:status
    |> Jsont.Obj.mem "tags"
         Jsont.(list string) ~dec_absent:[] ~enc:tags ~enc_omit:(( = ) [])
    |> Jsont.Obj.finish
end

Lists of task items can be serialized to strings with, for example, Jsont_codec:

let items = Jsont.list Item.jsont
let items_of_json s = Jsont_codec.decode_string items s
let items_to_json ?format is = Jsont_codec.encode_string ?format items is

If you are using js_of_ocaml the browser's built-in JavaScript parser can be used with Jsont_brr from the jsont.brr library:

let items_of_json s = Jsont_brr.decode items s
let items_to_json is = Jsont_brr.encode items is

The cookbook has more JSON modelling recipes and the topojson.ml in the repository provides a full example of a JSON schema modelisation.