Declarative JSON data manipulation for OCaml
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

at main 50 lines 1.6 kB view raw
1(*--------------------------------------------------------------------------- 2 Copyright (c) 2024 The jsont programmers. All rights reserved. 3 SPDX-License-Identifier: CC0-1.0 4 ---------------------------------------------------------------------------*) 5 6(* Examples from the docs *) 7 8let data = 9 {|{ "task": "Make new release", 10 "status": "todo", 11 "tags": ["work", "softwre"] }|} 12 13let () = 14 let p = Json.Path.(root |> mem "tags" |> nth 1) in 15 let update = Json.Codec.(set_path string p "software") in 16 let correct = 17 Result.map 18 (fun v -> Json.to_string ~preserve:true update v) 19 (Json.of_string ~meta:`Full update data) 20 in 21 print_endline (Result.get_ok correct) 22 23module Status = struct 24 type t = Todo | Done | Cancelled 25 26 let assoc = [ ("todo", Todo); ("done", Done); ("cancelled", Cancelled) ] 27 let codec = Json.Codec.enum ~kind:"Status" assoc 28end 29 30module Item = struct 31 type t = { task : string; status : Status.t; tags : string list } 32 33 let make task status tags = { task; status; tags } 34 let task i = i.task 35 let status i = i.status 36 let tags i = i.tags 37 38 let codec = 39 Json.Codec.Object.map ~kind:"Item" make 40 |> Json.Codec.Object.member "task" Json.Codec.string ~enc:task 41 |> Json.Codec.Object.member "status" Status.codec ~enc:status 42 |> Json.Codec.Object.member "tags" 43 Json.Codec.(list string) 44 ~enc:tags ~dec_absent:[] ~enc_omit:(( = ) []) 45 |> Json.Codec.Object.seal 46end 47 48let items = Json.Codec.list Item.codec 49let items_of_json s = Json.of_string items s 50let items_to_json ?indent is = Json.to_string ?indent items is