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.
Read values out of a document
Section titled “Read values out of a document”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 3cfasttrueThe accessors are get(&key), at(index), string(), int(), float(),
boolean(), list(), object() and is_null().
Match on the kind of value
Section titled “Match on the kind of value”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 1text twonullboolobject with 1 field(s)Build and print a document
Section titled “Build and print a document”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 ]}Reference
Section titled “Reference”import jsonFunctions
Section titled “Functions”pub fn parse(src: &Str) -> Json ! JsonErrorReads 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 valuenullpub fn quote(s: &Str) -> StrWraps text in double quotes and escapes it for JSON. Useful when writing JSON by hand.
pub fn text(j: &Json) -> Strpub fn num(v: i64) -> JsonA JSON number from an integer.
pub fn float(v: f64) -> JsonA 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.
pretty
Section titled “pretty”pub fn pretty(j: &Json) -> Strpretty 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.
Json.get
Section titled “Json.get”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.
Json.at
Section titled “Json.at”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.
Json.string
Section titled “Json.string”pub fn string(&self) -> Option<Str>The text of a JSON string; None for any other kind of value.
Json.int
Section titled “Json.int”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.
Json.float
Section titled “Json.float”pub fn float(&self) -> Option<f64>Any JSON number as f64; None for other kinds of value.
Json.boolean
Section titled “Json.boolean”pub fn boolean(&self) -> Option<bool>Json.list
Section titled “Json.list”pub fn list(&self) -> Option<&Vec<Json>>Json.object
Section titled “Json.object”pub fn object(&self) -> Option<&Vec<(Str, Json)>>The fields of an object, in the order they were written.
Json.is_null
Section titled “Json.is_null”pub fn is_null(&self) -> boolJson.to_str
Section titled “Json.to_str”pub fn to_str(&self) -> StrThe value as compact JSON text.
JsonError
Section titled “JsonError”pub struct JsonError { pub at: i64 pub message: Str}