Simdjsont.Codec
simdjsont · API reference
Codecs used to decode and encode typed OCaml values.
This module is the foundation for Decode, Encode, Extract.at, and Cbor. Define a codec once and reuse it across JSON strings, bigstrings, NDJSON streams, and CBOR bytes.
Typed codecs for JSON and CBOR.
A codec 'a t describes how to decode a parsed value into an OCaml value, how to encode that OCaml value as JSON, and how to turn it into the dynamic JSON tree used by CBOR encoding. The same codec can be used with JSON entry points such as decode_string and CBOR entry points such as Simdjsont.Cbor.decode_string.
Example: a record codec
type user = { id : int; name : string; email : string option }
let user : user Simdjsont.Codec.t =
let open Simdjsont.Codec in
Obj.field (fun id name email -> { id; name; email })
|> Obj.mem "id" int ~enc:(fun u -> u.id)
|> Obj.mem "name" string ~enc:(fun u -> u.name)
|> Obj.opt_mem "email" string ~enc:(fun u -> u.email)
|> Obj.finishHow object decoding works
- a decoder from a low-level raw element to
'a - an encoder from
'ato JSON written into a buffer - a conversion from
'ato the dynamic JSON tree Required fields fail with a path-aware error when they are absent or have the wrong type. Optional object members accept both a missing field and a presentnullvalue asNone. Unknown object members are ignored.
type error = {
path : string list;
message : string;
}Error value used by Decode_error.
pathis a list of strings accumulated during decoding.messageis a human-readable error message.
exception Decode_error of errorException raised by decoders.
val error_to_string : error -> stringConvert an error to a string.
type 'a tA codec for values of type 'a.
val decode_string : 'a t -> string -> ('a, string) resultdecode_string codec json parses json and decodes the root value using codec. The Error case contains either the simdjson parse message or a codec error such as "user.id: expected int".
val decode_string_exn : 'a t -> string -> 'aLike decode_string, but raises Failure with the error message. Prefer decode_string at trust boundaries.
val decode_bigstring :
'a t ->
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t ->
len:int ->
('a, string) resultdecode_bigstring codec buf ~len decodes the first len bytes of the bigstring buf using codec. Parsing is zero-copy when buf already has the padding required by the parser; otherwise the data is copied into a padded buffer.
val decode_bigstring_exn :
'a t ->
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t ->
len:int ->
'aLike decode_bigstring, but raises on error.
val decode_element :
'a t ->
Simdjsont__.Simdjsont_raw.element ->
('a, string) resultDecode an already parsed low-level element. The caller must keep the parser that owns element alive for the duration of the call.
val encode_to_obuf : 'a t -> 'a -> Simdjsont__.Simdjsont_obuf.tEncode a value into a fresh output buffer using the given codec.
val encode_string : 'a t -> 'a -> stringEncode a value to a JSON string using the given codec.
val encode_to_bigstring :
'a t ->
'a ->
(char, Bigarray.int8_unsigned_elt, Bigarray.c_layout) Bigarray.Array1.t * intEncode a value directly into a parse-ready bigstring, returning it with the number of valid bytes. No intermediate string is allocated, and the result can be fed straight back into decode_bigstring.
val to_json : 'a t -> 'a -> Simdjsont__.Simdjsont_json.tConvert a value to JSON AST using the given codec.
val null : unit tCodec for the JSON null value, represented as ().
val bool : bool tCodec for JSON booleans.
Simdjsont.Codec.decode_string Simdjsont.Codec.bool "true" = Ok trueval int : int tCodec for JSON integers mapped to OCaml int. Use int64 when the input may exceed the platform int range.
val int64 : int64 tCodec for JSON integers mapped to OCaml int64.
val float : float tCodec for JSON numbers mapped to OCaml float. Integer JSON numbers are accepted and converted to floats. Non-finite OCaml floats encode as null because JSON has no NaN or infinity literals.
val int32 : int32 tCodec for JSON integers mapped to OCaml int32. Decoding fails when the JSON number is not an integer or does not fit in 32 bits.
val nativeint : nativeint tCodec for JSON integers mapped to OCaml nativeint. Decoding fails when the JSON number is not an integer or does not fit in a nativeint (checked by round-trip).
val char : char tCodec for JSON strings of length 1 mapped to OCaml char. Decoding fails for strings whose length is not exactly 1.
val bytes : bytes tCodec for JSON strings mapped to OCaml bytes. Encoding and decoding are the same as string, converted with Bytes.of_string / Bytes.to_string.
val string : string tCodec for JSON strings. Encoding escapes control characters, quotes, and backslashes.
val list : 'a t -> 'a list tlist item maps JSON arrays to OCaml lists.
Simdjsont.Codec.decode_string Simdjsont.Codec.(list int) "[1,2,3]"
= Ok [ 1; 2; 3 ]val array : 'a t -> 'a array tarray item maps JSON arrays to OCaml arrays. Prefer list when you do not need random access or mutable array operations.
val optional : 'a t -> 'a option toptional codec maps null to None and any other value to Some decoded_value. When used with Obj.opt_mem, a missing object member also becomes None.
val map : ('a -> 'b) -> ('b -> 'a) -> 'a t -> 'b tmap decode encode codec adapts codec through conversion functions.
This is useful for small domain types:
type user_id = User_id of int
let user_id =
Simdjsont.Codec.map
(fun n -> User_id n)
(fun (User_id n) -> n)
Simdjsont.Codec.intval make :
decode:(string list -> Simdjsont__.Simdjsont_raw.element -> 'a) ->
encode:('a -> Simdjsont__.Simdjsont_obuf.t -> unit) ->
to_json:('a -> Simdjsont__.Simdjsont_json.t) ->
'a tmake ~decode ~encode ~to_json builds a codec from its three operations. This is the escape hatch used by generated code (and hand-written custom codecs) to define JSON mappings that cannot be expressed with the combinators above, such as tuples or sum types.
decode path eltdecodeselt, raisingDecode_error { path; message }on failure. Use afield :: pathextension when delegating to nested codecs viadecode_with_pathso errors keep their JSON path.encode v bufwrites the JSON representation ofvinto the existing output bufferbuf. Delegate to nested codecs withencode_into.to_jsonconvertsvto the dynamic JSON tree (used by CBOR encoding).
val decode_with_path :
'a t ->
string list ->
Simdjsont__.Simdjsont_raw.element ->
'adecode_with_path codec path elt decodes elt with an explicit error path prefix. Raises Decode_error on failure. Use this (rather than decode_element) when implementing make codecs so nested errors keep their full path.
val encode_into : 'a t -> 'a -> Simdjsont__.Simdjsont_obuf.t -> unitencode_into codec v buf writes the JSON encoding of v into the existing output buffer buf. Use this (rather than encode_to_obuf) when implementing make codecs so nested values share one buffer.
val fix : ('a t -> 'a t) -> 'a tfix f builds a recursive codec. f self must construct a codec that may mention self (only under decode/encode/to_json closures, which is how generated recursive codecs use it). The result delegates every operation through a single lazily-computed f self, so f runs once.
This exists because let rec c = ... c ... is rejected when the right-hand side is a codec combinator application rather than a function; fix moves the recursion inside the library where a record/lazy right-hand side is allowed. Generated code uses it for recursive monomorphic types.
val fix2 : (('a t * 'b t) -> 'a t * 'b t) -> 'a t * 'b tfix2 f is the two-way mutual-recursion analogue of fix. f (a, b) must construct the pair of codecs, possibly mentioning a and b under closures. The result pair delegates through one lazily-computed f (a,b). Generated code uses it for mutually recursive pairs of monomorphic types.
module Obj : sig ... endBuilder for JSON objects.
val value : Simdjsont__.Simdjsont_json.t tCodec for dynamic JSON values.
Use this when the document shape is not known at compile time, or when you want to transform a JSON/CBOR value tree manually before re-encoding it.