simdjsont — JSON encoding and decoding

Parse, validate and encode JSON in OCaml with simdjsont, using typed codecs, JSON pointers, NDJSON and zero-copy reads.

API reference

simdjsont reads and writes JSON. For reading, it wraps simdjson, a parser that uses SIMD instructions, which are CPU instructions that work on several bytes at once. It also provides typed codecs. A codec is one value per OCaml type that describes how to decode JSON into that type and encode values of that type back to JSON. Input that does not match a codec produces a decode error at the point where the codec runs.

Codecs describe both directions

examples/simdjsont_tour/main.ml
(* A codec describes both directions at once: how to decode a JSON
   object into a [user] and (via [~enc]) how to encode one back. *)
let user_codec =
  let open Simdjsont.Decode in
  Obj.field (fun id name active -> { id; name; active })
  |> Obj.mem "id" int ~enc:(fun u -> u.id)
  |> Obj.mem "name" string ~enc:(fun u -> u.name)
  |> Obj.mem "active" bool ~enc:(fun u -> u.active)
  |> Obj.finish

A codec is one value that describes both decoding JSON into an OCaml type and encoding values of that type as JSON. In the example above, Obj.field names the constructor. Each Obj.mem declares one member: its name, its type, and (via ~enc) how to read that member back out of the record when encoding. Obj.finish completes the codec. The field names, order and types are defined in one place and used for both decoding and encoding.

Validate, extract, decode, encode

This section covers four operations on the same document.

Validation

examples/simdjsont_tour/main.ml
(* [check] confirms a document parses, returning the parser's own
   diagnostic on failure. It does not decode values from the document. *)
(match Simdjsont.Validate.check json with
| Ok () -> Printf.printf "valid: %s\n" json
| Error e -> die ("validate: " ^ e));
(match Simdjsont.Validate.check "{broken" with
| Ok () -> die "expected \"{broken\" to be rejected"
| Error e -> Printf.printf "rejected \"{broken\": %s\n" e);

check confirms that a document parses and returns simdjson's diagnostic on failure. Use it when a yes-or-no answer is enough and no decoded value is needed. is_valid is the bool-returning variant.

Pointer extraction

examples/simdjsont_tour/main.ml
(* Read a single value by JSON pointer (RFC 6901) without decoding
   the whole document, for example to route on a discriminator field. *)
(match Simdjsont.Extract.string json ~pointer:"/name" with
| Ok name -> Printf.printf "pointer /name -> %s\n" name
| Error e -> die ("extract: " ^ e));

A JSON pointer is a path, like /user/id, that identifies one value inside a JSON document (RFC 6901). Extract follows that path and returns a single value without building the rest of the document. An application can read one discriminator field in this way and then choose which full codec to run. Extract has string, int, float, bool, is_null, and a codec-typed at.

Decode and encode

examples/simdjsont_tour/main.ml
(* Decode parses into the record; the same codec encodes a
   value back to a JSON string. *)
let alice =
  match Simdjsont.Decode.decode_string user_codec json with
  | Ok u ->
      Printf.printf "decoded: id=%d name=%s active=%b\n" u.id u.name u.active;
      u
  | Error e -> die ("decode: " ^ e)
in
let off_duty = { alice with active = false } in
Printf.printf "encoded: %s\n" (Simdjsont.Encode.to_string user_codec off_duty);

decode_string parses into the record; Encode.to_string serializes a value back. Decoding and encoding both use the same codec definition.

The combinator vocabulary

Codecs nest. A codec for a larger value can be built from codecs for its parts, using null, bool, int, float, string, list, array, optional, map, and the Obj builder with mem and opt_mem.

Lists, nesting, optional members

examples/simdjsont_nested/main.ml
(* Codecs nest: an [address] codec becomes a member of [person]. opt_mem
   handles a member that may be absent; list builds a homogeneous array;
   the whole thing is still one value describing both directions. *)
let address_codec =
  let open Simdjsont.Decode in
  Obj.field (fun city zip -> { city; zip })
  |> Obj.mem "city" string ~enc:(fun a -> a.city)
  |> Obj.mem "zip" string ~enc:(fun a -> a.zip)
  |> Obj.finish

let person_codec =
  let open Simdjsont.Decode in
  Obj.field (fun name age address tags -> { name; age; address; tags })
  |> Obj.mem "name" string ~enc:(fun p -> p.name)
  |> Obj.mem "age" int ~enc:(fun p -> p.age)
  |> Obj.opt_mem "address" address_codec ~enc:(fun p -> p.address)
  |> Obj.mem "tags" (list string) ~enc:(fun p -> p.tags)
  |> Obj.finish

An address codec becomes a member of person; list string decodes the tags array; opt_mem maps a member that may be absent to an option. map adapts a codec through a pair of functions when the JSON and OCaml shapes differ.

Decoding with missing members

examples/simdjsont_nested/main.ml
(match Simdjsont.Decode.decode_string person_codec json with
| Ok p ->
    Printf.printf "%s, %d, %d tags, address: %s\n" p.name p.age
      (List.length p.tags)
      (match p.address with Some a -> a.city | None -> "(none)")
| Error e -> die ("decode: " ^ e));
(* A document that omits the optional member still decodes. *)
(match
   Simdjsont.Decode.decode_string person_codec
     {|{"name":"Bo","age":20,"tags":[]}|}
 with
| Ok p -> Printf.printf "%s has no address: %b\n" p.name (p.address = None)
| Error e -> die ("decode: " ^ e));
$ dune exec examples/simdjsont_nested/main.exe

Streaming and zero-copy

This section covers streams of small documents and decoding directly from a buffer.

NDJSON streams

examples/simdjsont_tour/main.ml
  (* Decode newline-delimited JSON into a lazy sequence of typed
     results. A bad line yields an Error for that line. *)
  let ndjson =
    {|{"id": 2, "name": "Bob", "active": true}
{"id": 3, "name": "Carol", "active": false}
|}
  in
  print_endline "ndjson stream:";
  Simdjsont.Ndjson.decode_string_seq user_codec ndjson
  |> Seq.iter (function
       | Ok u -> Printf.printf "  user #%d %s (active=%b)\n" u.id u.name u.active
       | Error e -> die ("ndjson: " ^ e))

decode_string_seq turns newline-delimited JSON into a lazy Seq of typed results, with one Error element for each bad line. It can be used for log pipelines and bulk imports that process documents one at a time.

Decoding from a bigstring

examples/simdjsont_nested/main.ml
(* Decoding can read from a bigstring buffer, such as one filled by a
   socket, without allocating an intermediate OCaml string. *)
let buf = Simdjsont.bigstring_of_string json in
(match
   Simdjsont.decode_bigstring person_codec buf ~len:(String.length json)
 with
| Ok p -> Printf.printf "zero-copy decode: %s\n" p.name
| Error e -> die ("bigstring: " ^ e))

decode_bigstring works directly on the buffer the socket filled, without allocating an intermediate OCaml string. An araara JSON endpoint uses this function to decode a request body. Encode.to_bigstring provides the corresponding encoding function. The same codec also reads and writes CBOR, a binary encoding related to JSON, for messages that do not need to be human-readable.

Deriving codecs with ppx_simdjsont

The codecs on this page were built by hand. The ppx_simdjsont reference derives codecs from type definitions, including records with renames and defaults, variants, and generics. Derived codecs have the same type as handwritten codecs, so the helpers above can consume them.

Decoding at the application boundary

simdjsont is typically used where requests first arrive, before application logic runs. An API module decodes the request body into a domain type. If the JSON is malformed, the module returns a 400 response. The context behind that layer receives OCaml values from the API module. Under the web/API parity convention, each JSON endpoint has an HTML endpoint over the same context.