Danny Willems -- Work In Progress

Fighting to follow my values. Integrity is key. Reputation is key. Fighting for privacy and security on the Internet. Being respectful is your first duty.

Research Publications Public Talks Open source software contributions CV Education Blog PGP public key Recommended softwares Contact Proton calendar for cryptography and cybersecurity events
2 July 2018

How to manipulate JSON in OCaml?

by Danny Willems

Use PPX Deriving JSON. PPX is a syntax extension and PPX Deriving JSON derives functions when annotating a type to convert from and to JSON.

type person = {
  name: string;
  age: int;
} [@@deriving yojson]

will generate the functions

type person = { name : string; age : int; }
val person_to_yojson : person -> Yojson.Safe.json = <fun>
val person_of_yojson : Yojson.Safe.json -> person Ppx_deriving_yojson_runtime.error_or = <fun>

You can then play with the converters like this:

let x : person = {name = "hello"; age = 15};;
(* val x : person = {name = "hello"; age = 15} *)
person_to_yojson x;;
(* - : Yojson.Safe.json = `Assoc [("name", `String "hello"); ("age", `Int 15)] *)

If you use dune, you’ve got to use this

(library
 ((name test)
  (public_name test)
  (modules (test))
  (libraries (yojson ppx_deriving ppx_deriving.runtime
              ppx_deriving_yojson.runtime))
  (preprocess (pps (ppx_deriving ppx_deriving_yojson)))
))

If the type is called t, the functions are to_json and of_json

tags: OCaml - JSON - PPX - RSS