Jsont 8bc8442-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:

{ "task": "Make new release",
  "status": "todo",
  "tags": ["work"] }

We model them with OCaml and Jsont 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"
       ~dec_absent:[] ~enc_omit:(( = ) []) Jsont.(list string) ~enc:tags
    |> Jsont.Obj.finish
end

They can then be serialized to strings with for example Jsont_codec:

let items_of_json s = Jsont_codec.decode (Jsont.list Item.jsont) s
let items_to_json ?format items =
  Jsont_codec.encode ?format (Jsont.list Item.jsont) items

See more JSON modelling recipes in the cookbook.