Skip to content

Decoding

Decode a JSON profile, report invalid fields, and encode the checked value back to JSON. External data starts as Term; a decoder checks it at runtime and returns a value of the target type or validation errors.

A Decoder<A> is fn(Term) -> Result<A, List<ValidationError>>. Build one field at a time; validation.both combines independent checks and collects both errors when both fail, in source order. The target here is a plain struct:

Profile is a native named struct. Its required nickname field is Nilable<String>: JSON null maps to nil and text stays String. Missing keys remain a separate error.

mod decoding.profile
@moduledoc """
`Profile` is a native named struct. Its required `nickname` field is `Nilable<String>`:
JSON null maps to nil and text stays `String`. Missing keys remain a separate error.
"""
struct Profile {
name: String,
age: Integer,
tags: List<String>,
nickname: Nilable<String>
}

Decoder<A> checks a Term and returns a typed value or validation errors. Independent checks collect their errors in List<ValidationError>. The encoder chooses how the checked value is represented as JSON.

mod decoding
alias gale_std.decode
alias gale_std.validation
alias gale_std.result
alias gale_std.json
pub fn profile_decoder() -> decode.Decoder<decoding.profile.Profile> {
fn(input) -> {
name_age = validation.both(
decode.field(input, "name", decode.string()),
decode.field(input, "age", decode.integer())
)
tags_nickname = validation.both(
decode.field(input, "tags", decode.list(decode.string())),
decode.field(input, "nickname", decode.nullable(decode.string()))
)
result.map(validation.both(name_age, tags_nickname), fn(fields) -> {
{{name, age}, {tags, nickname}} = fields
%decoding.profile.Profile{
name: name, age: age, tags: tags, nickname: nickname
}
})
}
}
pub fn profile_encoder() -> json.Encoder<decoding.profile.Profile> {
fn(profile) -> json.object([
{"name", json.string(profile.name)},
{"age", json.integer(profile.age)},
{"tags", json.array(profile.tags, fn(tag) -> json.string(tag))},
{"nickname", json.nullable(profile.nickname, fn(name) -> json.string(name))}
])
}
pub fn decode_profile(source: String) -> Result<decoding.profile.Profile, json.JsonError> {
json.parse(source, profile_decoder())
}
pub fn encode_profile(profile: decoding.profile.Profile) -> String {
json.encode_with(profile, profile_encoder())
}

validation.both combines independent checks and can be nested for any number of fields. The constructor runs only when all checks succeed. Use with or and_else for dependent operations that stop at the first error.

Missing, present-and-null, and present-with-value are different things, and the decoder vocabulary says which: decode.nullable returns Nilable<A>, decode.optional returns Option<A>, and optional-nullable preserves all three states: None, Some(nil), Some(value). A required nilable field still rejects a missing key. Defaults apply to missing input only, never to malformed or null input unless you explicitly admit that.

Errors themselves are structured: a ValidationError carries a kind, an outer-to-inner path, expected/found descriptions and alternative context. Independent errors collect in field order; a malformed parent prevents child checks (no invented child failures, no partial success); Error([]) is still failure. And keep two failure kinds apart: JSON syntax errors (JsonError from parse) versus valid JSON with the wrong application shape (ValidationError lists).

The encoder above chooses the wire format: string keys, a JSON array for tags, and JSON null for a missing nickname. Keeping it beside the decoder makes the round trip visible. Neither a struct nor an arbitrary BEAM value is automatically JSON.

This project uses only gale_std. Reusable schema definitions and framework bindings are covered in the library reference.

The Json type is closed. Values outside it, such as a typed pid, cannot be passed to the encoder.