The js_of_ocaml-ppx_deriving_json package provides a PPX deriver for serializing OCaml values to JSON.
Important: The serialization format follows js_of_ocaml's internal representation. It is designed for communication between a js_of_ocaml program and a server-side OCaml application, not for interacting with third-party APIs.
opam install js_of_ocaml-ppx_deriving_json
Add [@@deriving json] to your type definitions:
type person = {
name : string;
age : int;
}
[@@deriving json]
(* Serialize to a JSON string *)
let json_str = Deriving_Json.to_string person_json { name = "Alice"; age = 30 }
(* Deserialize from a JSON string *)
let alice = Deriving_Json.from_string person_json json_strThe [@@deriving json] attribute generates:
person_to_json : Buffer.t -> person -> unit — write a value to a bufferperson_of_json : Deriving_Json_lexer.lexbuf -> person — read a value from a lexer bufferperson_json : person Deriving_Json.t — a witness, usable with Deriving_Json.to_string and Deriving_Json.from_string for string conversion (as in the example above)Note: For types named t, the prefix is omitted (e.g., of_json instead of t_of_json).
The [%to_json: type] and [%of_json: type] syntax also works with any type expression:
let json = [%to_json: int list] [1; 2; 3]
let nums = [%of_json: int list] jsonThe deriver supports:
int, float, string, bool'a option'a list, 'a array