package decoders-yojson
Module Safe.DecodeSource
The type of values to be decoded (e.g. JSON or Yaml).
The type of decoders.
Use the functions below to construct decoders for your data types.
To run a decoder, pass it to decode_value.
Primitives
Lists
Decode a collection into an OCaml list, skipping elements for which the decoder returns None.
Decode a collection with an accumulator.
If we consider that an 'a decoder is basically a type alias for json -> ('a, error) result, the signature of this function is comparable to that of List.fold_left:
val List.fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a
val list_fold_left : ('a -> json -> ('a, error) result) -> 'a -> json -> ('a, error) result
val list_fold_left : ('a -> 'a decoder) -> 'a -> 'a decoderObject primitives
Decode an object, where a particular field may or may not be present.
For example, (field_opt "hello" int):
- when run on
{"hello": 123}, will succeed withSome 123 - when run on
{"hello": null}, will fail - when run on
{"world": 123}, will succeed withNone - when run on
["a", "list", "of", "strings"], will fail
Decode an object, requiring exactly one field.
Decode a nested object, requiring certain fields.
Inconsistent structure
maybe d is a decoder that always succeeds. If d succeeds with x, then maybe d succeeds with Some x, otherwise if d fails, then maybe d succeeds with None.
For example, maybe (field "hello" int):
- when run on
{"hello": 123}, will succeed withSome 123 - when run on
{"hello": null}, will succeed withNone - when run on
{"world": 123}, will succeed withNone - when run on
["a", "list", "of", "strings"], will succeed withNone
nullable d will succeed with None if the JSON value is null. If the JSON value is non-null, it wraps the result of running x in a Some.
For example, field "hello" (nullable int):
- when run on
{"hello": 123}, will succeed withSome 123 - when run on
{"hello": null}, will succeed withNone - when run on
{"world": 123}, will fail - when run on
["a", "list", "of", "strings"], will fail
Mapping
Try two decoders and then combine the result. We can use this to decode objects with many fields (but it's preferable to use Infix.(>>=) - see the README).
Working with object keys
Decode an object into a list of key-value pairs.
Decode an object into a list of values, where the value decoder depends on the key.
keys' is for when your keys might not be strings - probably only likely for Yaml.
Fancy decoding
A decoder that always succeeds with the argument, ignoring the input.
A decoder that always fails with the given message, ignoring the input.
Create decoders that depend on previous results.
Recursive decoders.
let my_decoder = fix (fun my_decoder -> ...) allows you to define my_decoder in terms of itself.
Running decoders
Run a decoder on some input.
Run a decoder on a string.
Run a decoder on a file.