JSON
JSON is how programs that share nothing else — not a language, not a machine, not an owner — agree on what a value is. A web API answers in it, a browser stores settings in it, and a log line often is one. This lesson reads a JSON document with the Json package, takes typed values out of it, and shows how a broken document is refused.
import Allocator::{ Allocator, SystemAllocator };
import Json::{ JsonKind, JsonValue, Parse };
import Text::StringView;
Parsing a document
Parse reads the whole text into a tree of values:
Parse(allocator, text) -> JsonValue throws JsonParseError
The tree needs memory — a document can be any size — so Parse takes an allocator to get it from. Main makes the system allocator, which converts to an Allocator wherever one is wanted:
let allocator = SystemAllocator();
Parse either returns the whole document, as its root value, or throws the reason there is none. There is never half a document. The call sits in a try block, so the rest of the block runs only when the parse succeeded, and the catch arm takes the reason when it did not:
try {
let root = Parse(allocator, document);
Inspect(root);
} catch {
reason => PrintLine("refused at byte {}: {}", reason.Offset(), reason)
}
The document is one long string literal, with every " inside it escaped as \":
{ "name": "Rux", "year": 2026, "tags": ["fast", "small"], "flags": { "beta": true } }
A tree of six kinds
Every value in the tree is one of six kinds, and Kind() says which. Containers hold more values, so the document above parses into this tree:
flowchart TD
root["object"] -- "`name`" --> n["text: `Rux`"]
root -- "`year`" --> y["number: `2026`"]
root -- "`tags`" --> t["array"]
root -- "`flags`" --> f["object"]
t -- "`0`" --> t0["text: `fast`"]
t -- "`1`" --> t1["text: `small`"]
f -- "`beta`" --> b["boolean: `true`"]Reading the tree always means asking a value what it is before taking it apart. Every question answers an optional: none when the value is not what was asked for.
| Kind | Ask with | Answers |
|---|---|---|
Object | Find(name), Length() | a reference to the member, none if missing |
Array | At(index), Length() | a reference to the element, none past the end |
Text | AsText() | a StringView, none for any other kind |
Number | AsNumber(), then AsInt64 | none when the number is not that type |
Boolean | AsBoolean() | none when the value is not a boolean |
Null | IsNull() | true for null |
Length() is none for a value that is not a container, so the program writes root.Length() ?? 0 to fall back to zero. KindName turns a kind into a word for printing, with the _ arm covering the last one, Null.
Finding a member
Member names are text, so Find takes a StringView. A small Member method makes one from a literal:
extend JsonValue {
func Member(&self, name: char8[..]) -> &JsonValue? {
return self.Find(StringView::FromValidated(name));
}
}
Find answers a reference into the tree, or none when there is no such member. A reference that a function returns has to borrow from something, and a method's result borrows from its receiver — which is why Member is written in an extend block rather than as a free function.
Since the answer may be missing, the program tests it with is .Some(...) before reading it. Each test binds a name for the tests after it in the && chain, and for the body, so one if both finds the member and checks that it is text:
if root.Member("name") is .Some(name) && name.AsText() is .Some(text) {
PrintLine("name {}", text);
}
PrintLine("license present: {}", root.Member("license") is .Some(_));
The document has no license, and the program says so instead of crashing.
Numbers keep their text
JSON has one kind of number, and it does not say how big or how precise a number may be. So a JsonNumber keeps the text it was written with, and converting it is a question that may be answered none — the text may have a fraction, or not fit the type asked for:
if root.Member("year") is .Some(member) && member.AsNumber() is .Some(number) {
let year = number.AsInt64();
PrintLine("year {} (text \"{}\", fits an int64: {})", year ?? 0, number.Text(),
year is .Some(_));
}
AsNumber answers the number, or none if the value were some other kind, and AsInt64 answers the int64, or none if the text does not fit one.
Arrays and nested objects
An array is walked by index, and each element is asked its kind like any other value. A nested object is just another value with members of its own:
if root.Member("tags") is .Some(tags) {
for i in 0..(tags.Length() ?? 0) {
if tags.At(i) is .Some(tag) && tag.AsText() is .Some(text) {
PrintLine("tags[{}] {} {}", i, KindName(tag.Kind()), text);
}
}
}
if root.Member("flags") is .Some(flags) && flags.Member("beta") is .Some(beta) {
let value = beta.AsBoolean();
PrintLine("beta boolean: {}, value: {}", value is .Some(_), value ?? false);
}
Every member is checked, even though the document is a literal in the program and they are known to be there. The types leave no other way to read them: an optional has to be unwrapped before its value can be used, so a document from outside cannot crash the program with a member it lacks.
Malformed input
JSON is strict, and Parse refuses anything that is not exactly JSON. The error says why, and at which byte the parser stopped. Check parses each document in a try block of its own and prints what happened:
| Document | Refused at | Because |
|---|---|---|
[1, 2, 3,] | byte 9 | a trailing comma: ] cannot follow , |
{'name': 'Rux'} | byte 1 | single quotes begin no token in JSON |
{"open": [1, 2} | byte 14 | } cannot close an array |
{"a": 1} extra | byte 9 | text after the end of the document |
| (empty) | byte 0 | the document ended before any value began |
Offsets count from zero, so byte 9 is the tenth. A message that names the byte lets a person go straight to the mistake.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// JSON is how programs that share nothing else agree on what a value is. The Json package reads
// a document into a tree of `JsonValue`s, and every value in the tree is one of six kinds: text,
// number, boolean, null, array or object.
//
// Parse(allocator, text) -> JsonValue throws JsonParseError
//
// Parsing hands back a whole document or throws the reason there is none, never half of one.
// Reading the tree then means asking a value what it is before taking it apart: `Find` and `At`
// answer `none` when the member or element is not there, and the conversions answer `none` when
// the value is some other kind.
import Allocator::{ Allocator, SystemAllocator };
import Io::PrintLine;
import Json::{ JsonKind, JsonValue, Parse };
import Text::StringView;
func KindName(kind: JsonKind) -> char8[..] {
return match kind {
JsonKind::Text => "text",
JsonKind::Number => "number",
JsonKind::Boolean => "boolean",
JsonKind::Array => "array",
JsonKind::Object => "object",
_ => "null"
};
}
// Member names are compared as text, so `Find` takes a `StringView`. The answer borrows from the
// value it was found in, so it is an optional reference, and the helper is a method: a reference
// result borrows from the receiver.
extend JsonValue {
func Member(&self, name: char8[..]) -> &JsonValue? {
return self.Find(StringView::FromValidated(name));
}
}
func Inspect(root: &JsonValue) {
PrintLine("root {} of {} members", KindName(root.Kind()), root.Length() ?? 0);
// A member that is not there is `none`, so check before reading it. Each `is` test binds a
// name for the tests after it in the `&&` chain, and for the body.
if root.Member("name") is .Some(name) && name.AsText() is .Some(text) {
PrintLine("name {}", text);
}
PrintLine("license present: {}", root.Member("license") is .Some(_));
// A number keeps the text it was written with, and converting it is a question that can
// be answered `none`: the text may have a fraction, or not fit the type asked for.
if root.Member("year") is .Some(member) && member.AsNumber() is .Some(number) {
let year = number.AsInt64();
PrintLine("year {} (text \"{}\", fits an int64: {})", year ?? 0, number.Text(),
year is .Some(_));
}
// An array is walked by index, and each element is asked its kind like any other value.
if root.Member("tags") is .Some(tags) {
for i in 0..(tags.Length() ?? 0) {
if tags.At(i) is .Some(tag) && tag.AsText() is .Some(text) {
PrintLine("tags[{}] {} {}", i, KindName(tag.Kind()), text);
}
}
}
// A nested object is just another value with members of its own.
if root.Member("flags") is .Some(flags) && flags.Member("beta") is .Some(beta) {
let value = beta.AsBoolean();
PrintLine("beta boolean: {}, value: {}", value is .Some(_), value ?? false);
}
}
// `Parse` throws, so the parse sits in a `try` block, and the `catch` arm takes the reason.
func Check(allocator: Allocator, document: char8[..]) {
try {
let root = Parse(allocator, document);
PrintLine("{:18} parsed as {}", document, KindName(root.Kind()));
} catch {
reason => PrintLine("{:18} refused at byte {}: {}", document, reason.Offset(), reason)
}
}
func Main() -> int {
let allocator = SystemAllocator();
let document =
"{\"name\":\"Rux\",\"year\":2026,\"tags\":[\"fast\",\"small\"],\"flags\":{\"beta\":true}}";
try {
let root = Parse(allocator, document);
Inspect(root);
} catch {
reason => PrintLine("refused at byte {}: {}", reason.Offset(), reason)
}
// Malformed input. The failure says why, and the byte where the parser stopped, so a message
// to a person can point at the problem. JSON is strict: no trailing commas, no single quotes.
PrintLine("");
Check(allocator, "[1, 2, 3]");
Check(allocator, "[1, 2, 3,]");
Check(allocator, "{'name': 'Rux'}");
Check(allocator, "{\"open\": [1, 2}");
Check(allocator, "{\"a\": 1} extra");
Check(allocator, "");
return 0;
}
Besides Io, its Rux.toml lists Allocator, Json and Text under [Dependencies].
Run it
cd Examples/DataFormats/Json
rux run
root object of 4 members
name Rux
license present: false
year 2026 (text "2026", fits an int64: true)
tags[0] text fast
tags[1] text small
beta boolean: true, value: true
[1, 2, 3] parsed as array
[1, 2, 3,] refused at byte 9: token that cannot appear here
{'name': 'Rux'} refused at byte 1: byte that begins no token
{"open": [1, 2} refused at byte 14: token that cannot appear here
{"a": 1} extra refused at byte 9: text after the end of the document
refused at byte 0: document ended in the middle of a value
Common mistakes
Try it yourself
- Add
"license": nullto the document. Check it withIsNull(). - Add
"version": 1.5. What doAsInt64andAsFloat64each answer for it? - Pass
{"a": 1, "a": 2}toCheck. JSON does not forbid a repeated name — but what does this parser do with one? - List every member of the root object with
MemberAt(i), printing each one'snameand the kind of itsvalue.
Learn more
- JSON write — building a tree and writing it back out as text
- JSON stream — reading a document without building the tree
- Presence and Coalesce — testing the optionals that
Find,Atand the conversions answer - Allocator — where the tree's memory comes from
- Matching optionals and try blocks in the Rux Reference
Overview
Read and write JSON and TOML, write bytes as Base64 and its relatives, take URLs apart and put them together, and compress data: eight lessons on the formats programs exchange.
21.2 Writing JSON
Build a JSON value by hand, write it compact and pretty with WriteValue, parse the output back to the same text, and see a number JSON cannot spell refused.