Json_encoding Ppx deriver

ppx_deriving_encoding is a json-encoding ppx deriver.

type x = {
  a : string;
  b : int list;
  c : Ezjsonm.value option;
} [@@deriving encoding]

will produce the encoding:

let x_enc : x encoding =
  conv
    (fun {a; b; c} -> (a, b, c))
    (fun (a, b, c) -> {a; b; c})
    (obj3
      (req "a" string)
      (req "b" (list int))
      (opt "c" any_ezjson_value))

Most of regular json types are handled. GADT and variant inheritance are not handled yet.

Field Options

General options

Tuple options

Variant options

If it is not a string enumeration, any constructor or polymorphic variant will produce a union encoding. Any case of the union can receive [@title expr], [@description expr], [@kind "kind"] attributes.

[@kind "kind_name"] will add the encoding

(obj1 (req "kind" (constant "kind_name")))

to allow several constructor with the same type to be well desctructed.

If the string literal is omitted, the kind name will be derived from the constructor name. The label can also be changed from "kind" using [@kind_label "kind_label_name"].

For an empty constructor, the default behaviour will use the constant encoding with the name derived from the name of the constructor. It can be set to empty with the [@empty] attribute.

type t =
  | A of x [@kind "a"]
  | B of y
  | C of x [@kind]
  | D of z [@kind "bla"] [@kind_label "category"]
  | E
  | F [@empty]
[@@deriving encoding]

will produce :

let enc =
  union [
    case
      (conv (fun x -> (), x) (fun ((), x) -> x)
        (merge_objs (obj1 (req "kind" (constant "a"))) x_enc))
      (function A x -> Some x | _ -> None)
      (fun x -> A x);
    case
      y_enc
      (function B x -> Some x | _ -> None)
      (fun x -> B x);
    case
      (conv (fun x -> (), x) (fun ((), x) -> x)
        (merge_objs (obj1 (req "kind" (constant "c"))) x_enc))
      (function C x -> Some x | _ -> None)
      (fun x -> C x);
    case
      (conv (fun x -> (), x) (fun ((), x) -> x)
        (merge_objs (obj1 (req "category" (constant "bla"))) z_enc))
      (function D x -> Some x | _ -> None)
      (fun x -> D x);
    case
      (constant "e")
      (function E -> Some () | _ -> None)
      (fun () -> E);
    case
      empty
      (function F -> Some () | _ -> None)
      (fun () -> F);
  ]

Top type options

Compilation environnement variables

Here are some environnement variables that can be useful: