JSON arrives without an appointment
A document can be perfectly valid JSON and still have very little to do with the value your program needs.
The parser has checked the punctuation. It has not checked whether a bird's age is a number, or whether the bird remembered to bring its name.
Pooka's JSON library keeps those two questions separate.
Describe the value you want
This class gives the application a value to work with. The decoder says how to find one in a JSON document:
module main
import pooka/json/decode
class Bird(name: String, age: Int)
bird() -> decode.Decoder(Bird) {
decode.map2(
decode.field("name", decode.string()),
decode.field("age", decode.int()),
Bird
)
}
map2 combines two successful readings with the class constructor. The resulting recipe returns a Bird; callers do not need to keep asking a general JSON value whether it happens to contain an integer today.
Add a small main below it:
main() {
let text = "{\"name\":\"Ada\",\"age\":3}"
let assert Ok(visitor) = decode.read(text, bird())
assert visitor.name == "Ada"
assert visitor.age == 3
let wrong = "{\"name\":\"Ada\",\"age\":\"three\"}"
let assert Error(problem) = decode.read(wrong, bird())
assert decode.describe(problem) == "$/age: expected integer, found string"
}
Broken JSON produces a syntax failure. Valid JSON with the wrong application shape produces a shape failure. Field and array paths survive the journey, so an error can point to age rather than declaring the entire document suspicious.
Let the class choose what leaves
Encoding has an interface too. In a separate source file, an application class can choose its public representation:
module main
import pooka/json.{Encodable}
class Bird(name: String) with Encodable {
to_json() -> json.Json {
json.JObject([#("name", json.JString(name))])
}
}
main() {
assert json.encode_value(Bird("Ada")) == "{\"name\":\"Ada\"}"
}
The class chooses fields. The writer handles escaping and punctuation. Adding a private implementation field need not change the JSON your users receive.
Keep the boundary honest
Parsing uses Erlang's native JSON parser and builds the typed Pooka tree directly. Objects retain field order and duplicate keys; field lookup uses the first occurrence.
The stdlib's pooka/dynamic/decode serves another boundary: arbitrary BEAM values. It is useful when reading foreign maps and tuples. pooka/json/decode works over the JSON family, with its own object and number rules. Turning everything into a foreign map would lose some of those choices.
For untrusted documents, use read_with_limits to set byte and container-depth bounds before application decoding. Types are useful at the door. A size limit is useful before somebody tries to carry the entire forest through it.
The JSON documentation has the other recipes.
— Peregrine Finch