ppx_simdjsont — derived codecs
Derive simdjsont JSON codecs in OCaml with ppx_simdjsont for records, variants and generic types from type definitions.
A handwritten simdjsont codec names each member for decoding and for encoding. ppx_simdjsont derives both from the type definition. Each annotated type generates a codec and string helpers. A nested type derives its own codec, which is composed into the enclosing type's codec. Derived codecs are ordinary Simdjsont.Codec.t values and can be used alongside handwritten ones. The examples below cover records, variants and generics.
Setup
Install the deriver next to simdjsont:
$ opam install simdjsont ppx_simdjsontEnable it where your types live:
(executable
(name main)
(libraries simdjsont)
(preprocess (pps ppx_simdjsont)))
; Executed by `dune runtest`: the example must run to completion.
(rule
(alias runtest)
(action
(run ./main.exe)))Records
The example record has a renamed member, a decode default, an option and a list. One annotation on the definition generates the codec:
(* Nested records with a renamed member, a decode default, an option
and a list. Each record derives its own codec; they compose. *)
type tls = { enabled : bool; cert : string option } [@@deriving simdjsont]
type server = {
host : string; [@key "hostName"]
port : int; [@default 80]
tls : tls;
tags : string list;
}
[@@deriving simdjsont]Decoding fills in the default port and accepts a missing cert as None. Encoding writes the defaulted member and omits a None option:
(* Decoding fills the default port and accepts a missing cert as None;
encoding writes port and omits a None cert. *)
let srv =
check "server"
(server_of_string
{|{"hostName":"db.internal","tls":{"enabled":true},"tags":["primary","eu"]}|})
in
assert (srv.host = "db.internal" && srv.port = 80);
assert (srv.tls.enabled && srv.tls.cert = None);
Printf.printf "server: host=%s port=%d tags=%d\n" srv.host srv.port
(List.length srv.tags);
let json =
server_to_string
{
host = "db.internal";
port = 80;
tls = { enabled = true; cert = None };
tags = [ "primary" ];
}
in
expect "server json"
{|{"hostName":"db.internal","port":80,"tls":{"enabled":true},"tags":["primary"]}|}
json;
print_endline json;[@key] renames a member (alias [@name]); [@default expr] decodes a missing member as expr, and encoding still writes the member; [@codec expr] overrides one member's codec.
Variants
Nullary constructors encode as strings; constructors with payloads encode as ["Tag", args...], with per-constructor renames:
(* Nullary constructors encode as strings; payloads encode as
["Tag", args...]. Tags rename with [@name]. *)
type shape = Circle of float | Rect of float * float | Point
[@@deriving simdjsont]
type msg = Ping [@name "ping"] | Text of string [@name "text"]
[@@deriving simdjsont](* Variants round-trip through their string and array forms. *)
expect "nullary" {|"Point"|} (shape_to_string Point);
expect "payload" {|["Rect",1.5,2.5]|} (shape_to_string (Rect (1.5, 2.5)));
expect "renamed nullary" {|"ping"|} (msg_to_string Ping);
expect "renamed payload" {|["text","hello"]|} (msg_to_string (Text "hello"));
(match msg_of_string {|["text","hello"]|} with
| Ok (Text "hello") -> print_endline {|decoded: Text "hello"|}
| Ok _ ->
prerr_endline "error: wrong message payload";
exit 1
| Error e ->
Printf.eprintf "error: decode message: %s\n" e;
exit 1);Generics
Each type parameter becomes a codec argument:
(* Each type parameter becomes a codec argument. *)
type 'a page = { items : 'a list; total : int } [@@deriving simdjsont](* One generic definition serves every element type. *)
let ints = { items = [ 1; 2 ]; total = 2 } in
let encoded = page_to_string Simdjsont.Codec.int ints in
expect "page json" {|{"items":[1,2],"total":2}|} encoded;
let back = check "page" (page_of_string Simdjsont.Codec.int encoded) in
assert (back.items = [ 1; 2 ] && back.total = 2);
Printf.printf "page: %s\n" encodedRecursive and mutually recursive types can also be derived. For other shapes, including polymorphic variants, GADTs and custom member mappings, override the member with [@codec] or write a manual codec with Codec.make.
$ dune exec examples/simdjsont_ppx/main.exeIn a full application, an API module uses derived codecs where requests arrive. It decodes a request body into a domain type with
*_of_string, or returns a 400 response when decoding returns an error. Code behind the API module receives OCaml values. The API reference linked above documents the deriver functions and attributes.