Consider a structure like this:
type internalObj = {name: string}
type obj = {
id: string,
internal: option<internalObj>,
}
I already know that the property obj.internal might be missing and I want to decode that to an Option.
I also know that the property internalObj.name can be missing but I want it to always have a default value.
This is how I would write a decoder for the name property with a default value:
let internalObj_decode: Json.Decode.t<internalObj> = {
open Json.Decode
map(option(field("name", string)), ~f=name => {
name: name->Belt.Option.getWithDefault("Default Name"),
})
}
And this works fine!
But if the decoder for "obj" considers that "internal" is nullable:
let decoder: Json.Decode.t<obj> = {
open Json.Decode
map2(field("id", string), field("internal", nullable(internalObj_decode)), ~f=(
id,
internal,
) => {
id: id,
internal: internal,
})
}
I would expect the decoder for internal to not run if the value is null, like { "id": "123", "internal": null }, but it runs.
Shouldn't nullable prevent running the decoder if the value is null?
Consider a structure like this:
I already know that the property
obj.internalmight be missing and I want to decode that to an Option.I also know that the property
internalObj.namecan be missing but I want it to always have a default value.This is how I would write a decoder for the name property with a default value:
And this works fine!
But if the decoder for "obj" considers that "internal" is nullable:
I would expect the decoder for
internalto not run if the value isnull, like{ "id": "123", "internal": null }, but it runs.Shouldn't nullable prevent running the decoder if the value is
null?