module always in scope
Json
A parsed JSON document. Json.parse reads one from text, the accessors take it apart, and Json.render turns any nib value into JSON text.
Json is a JSON document as a value: an object, array, string, number, true, false or null. Its shape is not known to the checker, so the accessors that look inside one — Json.field, Json.text, Json.items — check the shape when they run and raise when it is not what they expected.
The two directions are separate functions. Json.parse and Json.stringify go from JSON text to a document and back; Json.render goes from any nib value — a record, a Map, a Vec — straight to JSON text.
let doc = Json.parse("\x7b\"user\": \x7b\"name\": \"ada\"}, \"admin\": true}");
let name = Json.text(Json.field(doc, "user"), "name");
Json.render(#{ greeting: "hello, " ++ name, admin: Json.field(doc, "admin") })
{"greeting":"hello, ada","admin":true}
A JSON object starts with {, which in a nib string literal opens an interpolation splice, so the examples on this page write it as the escape \x7b.
A document prints as compact JSON text.
Functions
func parse :: String -> Json raises Err.InvalidJson
Reads JSON text into a document. Raises Err.InvalidJson, with a message giving the byte offset of the problem, when the text is not valid JSON.
Json.parse("\x7b\"name\": \"nib\", \"tags\": [1, 2.5, true, null]}")
{"name":"nib","tags":[1,2.5,true,null]}
try Json.stringify(Json.parse("[1, 2"))
rescue Err.InvalidJson(msg) => "invalid: {msg}" end
invalid: byte 5: expected ',' or ']'
func field :: Json, String -> Json raises Err.MissingField, Err.NotAnObject
The value of member key in an object, as a document. If the object has the same key more than once, the first one wins.
Raises Err.MissingField when the object has no such member, and Err.NotAnObject when the document is not an object at all.
let doc = Json.parse("\x7b\"user\": \x7b\"name\": \"ada\"}, \"n\": 3}");
(Json.field(doc, "user"), Json.field(doc, "n"))
({"name":"ada"}, 3)
let doc = Json.parse("[1, 2]");
try Json.stringify(Json.field(doc, "a"))
rescue Err.NotAnObject(msg) => msg end
Json.field needs an object, this document is a List
func text :: Json, String -> String raises Err.MissingField, NotAString, Err.NotAnObject
The value of member key in an object, as a nib String — the usual way to read a string field. Raises Err.MissingField and Err.NotAnObject exactly as Json.field does.
When the member exists but is not a JSON string, text stops the program with NotAString. That is a panic, not an error: it must still be listed in the caller's raises row, but a rescue arm cannot name it — only a catch-all rescue _ arm takes it. If a field's type is not certain, read it with Json.field instead.
let doc = Json.parse("\x7b\"name\": \"ada\", \"age\": 36}");
Json.text(doc, "name")
ada
let doc = Json.parse("\x7b\"name\": \"ada\", \"age\": 36}");
try Json.text(doc, "age") rescue _ => "age is not a string" end
age is not a string
func int :: Json, String -> Int raises Err.MissingField, Err.WrongType, Err.NotAnObject
The value of member key in an object, as an Int. Raises Err.MissingField and Err.NotAnObject exactly as Json.field does, and Err.WrongType when the member is there but is not a whole number. Unlike Json.text's panic, WrongType can be rescued: a document from somewhere else is input, and input of the wrong shape is a case to handle.
let doc = Json.parse("\x7b\"name\": \"ada\", \"age\": 36}");
Json.int(doc, "age") + 1
37
let doc = Json.parse("\x7b\"name\": \"ada\", \"age\": 36}");
try Json.int(doc, "name") rescue Err.WrongType(m) => -1 end
-1
func bool :: Json, String -> Bool raises Err.MissingField, Err.WrongType, Err.NotAnObject
The value of member key in an object, as a Bool. Raises as Json.int does, Err.WrongType for a member that is not true or false.
let doc = Json.parse("\x7b\"granted\": true}");
Json.bool(doc, "granted")
true
func string :: Json, String -> String raises Err.MissingField, Err.WrongType, Err.NotAnObject
The value of member key in an object, as a String, with Err.WrongType for a member that is not a string. It is Json.text with a failure a rescue arm can name, which is what code that reads another program's messages wants.
let doc = Json.parse("\x7b\"name\": \"ada\", \"age\": 36}");
try Json.string(doc, "age") rescue Err.WrongType(_) => "not a string" end
not a string
func items :: Json -> List<Json> raises Err.NotAList
The elements of a JSON array, in order, as a List<Json>. Raises Err.NotAList when the document is not an array. A List is taken apart with match, as below.
match (Json.items(Json.parse("[\"first\", \"second\"]")))
[] => "empty"
[head, ...rest] => Json.stringify(head)
end
"first"
try Json.items(Json.parse("42")) == []
rescue Err.NotAList(msg) => false end
false
func stringify :: Json -> String
The document as JSON text: compact, with no extra whitespace, and with object members in the order the source had them. Text that came from Json.parse goes through stringify and parse again unchanged; duplicate keys are written out as they were, not merged.
Json.stringify(Json.parse(" \x7b \"b\" : 1, \"a\" : [ 1 , 2 ], \"b\": 3 } "))
{"b":1,"a":[1,2],"b":3}
func render :: 'a -> String raises Err.Unrenderable
Any nib value as JSON text. Records and Maps become objects — a record keeps its fields in the order written, a Map its keys in sorted order. Vecs, lists, tuples and Sets become arrays; () becomes null; a String is escaped as JSON requires; and a Json document renders as itself.
Raises Err.Unrenderable for a value with no JSON spelling: a function, a data variant, a Bytes value (convert it with Bytes.to_string first), a Symbol, a Fiber, or a Float that is infinite or not a number.
Json.render(#{ name: "nib", tags: #["a", "b"], ok: true, none: (), scores: {"x": 1.5}, ids: #{2, 1} })
{"name":"nib","tags":["a","b"],"ok":true,"none":null,"scores":{"x":1.5},"ids":[1,2]}
Json.render("say \"hi\"\n")
"say \"hi\"\n"
try Json.render(#{ cb: { x -> x + 1 } })
rescue Err.Unrenderable(msg) => msg end
a function has no JSON spelling