Skip to content

json

Read and write JSON. A parsed document is a Json value: an enum with one variant per kind of JSON value, which you take apart with its methods or with match. The methods return an Option: int() on a string, get(&"key") on a list or a missing key give None, so a wrong or missing value can never pass for 0 or "".

Numbers are kept as the text they were written with (Json.Num("1.50")), so large ids and exact decimals pass through unchanged. Objects are a list of (key, value) pairs in their original order.

import json
let doc = try json.parse("{\"name\": \"brass\", \"version\": 3, \"tags\": [\"c\", \"fast\"], \"stable\": false}")
let name = doc.get(&"name").unwrap().string().unwrap_or("?")
match doc.get(&"version") {
Some(v) => print(f"{name} {v.int().unwrap_or(0)}")
None => print(name + " (no version)")
}
match doc.get(&"tags") {
Some(tags) => {
for t in tags.list().unwrap_or(&[]) {
print(t.string().unwrap_or("?"))
}
}
None => print("no tags")
}
print(f"{doc.get(&"stable").unwrap().int().is_none()}")
brass 3
c
fast
true

The accessors are get(&key), at(index), string(), int(), float(), boolean(), list(), object() and is_null().

import json
let doc = try json.parse("[1, \"two\", null, true, {\"k\": []}]")
for item in doc.list().unwrap() {
let kind = match item {
json.Json.Null => "null"
json.Json.Bool(_) => "bool"
json.Json.Num(n) => f"number {n}"
json.Json.Text(s) => f"text {s}"
json.Json.List(_) => "list"
json.Json.Object(fields) => f"object with {fields.len()} field(s)"
}
print(kind)
}
number 1
text two
null
bool
object with 1 field(s)

text writes compact JSON; pretty writes it over several lines.

import json
let doc = json.Json.Object([
("name", json.Json.Text("brass")),
("version", json.num(3)),
("tags", json.Json.List([json.Json.Text("c"), json.Json.Bool(true)])),
])
print(json.text(&doc))
print(json.pretty(&doc))
{"name":"brass","version":3,"tags":["c",true]}
{
"name": "brass",
"version": 3,
"tags": [
"c",
true
]
}
import json
pub fn parse(src: &Str) -> Json ! JsonError

Reads one JSON value; anything but space after it is an error.

The whole text must be one JSON value; anything but white space after it is an error. A JsonError gives the byte offset (at) and a message.

import json
let doc = json.parse("{\"a\": }") catch {
json.JsonError(e) => {
print(f"bad JSON at byte {e.at}: {e.message}")
json.Json.Null
}
}
print(json.text(&doc))
bad JSON at byte 6: expected a value
null
pub fn quote(s: &Str) -> Str

Wraps text in double quotes and escapes it for JSON. Useful when writing JSON by hand.

pub fn text(j: &Json) -> Str
pub fn num(v: i64) -> Json

A JSON number from an integer.

pub fn float(v: f64) -> Json

A JSON number from a float; NaN and infinities have no JSON form and become null.

A NaN or an infinity has no JSON form, so it becomes null.

pub fn pretty(j: &Json) -> Str

pretty lays a value out over lines, two spaces per level, for people to read.

pub enum Json {
Null
Bool(bool)
Num(Str)
Text(Str)
List(Vec<Json>)
Object(Vec<(Str, Json)>)
}

A JSON value; numbers keep their text, so large ids and exact decimals are not rounded.

pub fn get(&self, key: &Str) -> Option<&Json>

The value under key in an object; None for a missing key or a value that is not an object.

Looks up a key in an object. Returns None for a missing key and for anything that is not an object. With duplicate keys, the first one wins.

pub fn at(&self, index: i64) -> Option<&Json>

The item at index in a list; None past the end or for a value that is not a list.

pub fn string(&self) -> Option<Str>

The text of a JSON string; None for any other kind of value.

pub fn int(&self) -> Option<i64>

A number that is a whole i64 (3, not 3.5 or 1e400); None otherwise.

Only a whole number that fits an i64 gives Some: 1.5, 1e3 and 1e400 give None. Use float() for those.

pub fn float(&self) -> Option<f64>

Any JSON number as f64; None for other kinds of value.

pub fn boolean(&self) -> Option<bool>
pub fn list(&self) -> Option<&Vec<Json>>
pub fn object(&self) -> Option<&Vec<(Str, Json)>>

The fields of an object, in the order they were written.

pub fn is_null(&self) -> bool
pub fn to_str(&self) -> Str

The value as compact JSON text.

pub struct JsonError {
pub at: i64
pub message: Str
}