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.
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.
jsont
Jsont
Types for JSON values.jsont.bytesrw
This library depends on the bytesrw
library and exports the jsont
library.
Jsont_bytesrw
JSON codec.jsont.brr
This 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_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.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) ~dec_absent:[] ~enc:tags ~enc_omit:(( = ) [])
|> Jsont.Object.finish
end
Lists 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 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, the topojson.ml
and geojson.ml
in the source repository provide full examples of JSON schema modelisation.