type sex = Male | Female
type tp = {
name: string;
age: int;
sex: sex
}
and we want to decode the javascript object
{name: "Jonathan", sex: "male", age: 55}
The we can use the following decoder
let decode: tp Decode.t =
let open Decode in
let* name = field "name" string in
let* age = field "age" int in
let* sex =
field
"sex"
(
let* str = string in
match str with
| "male" ->
return Male
| "female" ->
return Female
| _ ->
fail
)
in
return {name; age; sex}
The decoder decode decodes any javascript object which has the fields nameage and sex with a value of the appropriate type into the corresponding ocaml record.
General
type'a t
'a t Type of a decoder which decodes a javascript value into an optional object of type 'a.
option dec In case the javascript object is null succeed with None. Otherwise use dec to decode the object and in case of success wrap the result with Some.
Examples:
run (option int) Value.null ~> Some None
run (option int) (Value.int 5) ~> Some (Some 5)
run (option int) (Value.string "a") ~> None