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.
The following manuals are available.
Jsont cookbook has a few conventions and JSON data modelling recipes.The test directory in the source repository of Jsont has a few more examples.
jsontJsont Types for JSON values.jsont.bytesrwThis library depends on the bytesrw library and exports the jsont library.
Jsont_bytesrw JSON codec.jsont.brrThis library depends on the brr library and exports the jsont library.
Jsont_brr JavaScript support.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_bytesrw.recode_string ~layout:true update data in
print_endline (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.Object.map ~kind:"Item" make
|> Jsont.Object.mem "task" Jsont.string ~enc:task
|> Jsont.Object.mem "status" Status.jsont ~enc:status
|> Jsont.Object.mem "tags" Jsont.(list string) ~enc:tags
~dec_absent:[] ~enc_omit:(( = ) [])
|> Jsont.Object.finish
endLists of task items can be serialized to strings with, for example, Jsont_bytesrw:
let items = Jsont.list Item.jsont
let items_of_json s = Jsont_bytesrw.decode_string items s
let items_to_json ?format is = Jsont_bytesrw.encode_string ?format items isIf 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 isThe cookbook has more JSON modelling recipes, the topojson.ml, geojson.ml, json_rpc.ml, in the source repository provide full examples of JSON schema modelisations.