std/json
Zero-copy JSON parser with typed accessors.
from "std/json" import { Json }Types
Json
struct Json {
source: string,
nodes: Vec<JsonNode>,
childIdx: Vec<i64>,
keyOffsets: Vec<i64>,
keyLens: Vec<i64>,
root: i64,
}A parsed document: one flat pool of nodes over the original source, plus the index side-tables the accessors walk. Strings and numbers are stored as offsets into source, not copies, so a Json value is cheap to pass around and every accessor returns a view rather than allocating. Treat the fields as internal — use the accessors below.
Json.get
fn get(self, key: &string): Option<Json>Look up an object key, returning a Json view of the value.
Json.str
fn str(self, key: &string): Option<string>Get a string value by key.
Json.i64
fn i64(self, key: &string): Option<i64>Get an integer value by key.
Json.f64
fn f64(self, key: &string): Option<f64>Get a float value by key.
Json.bool
fn bool(self, key: &string): Option<bool>Get a boolean value by key.
Json.asStr
fn asStr(self): Option<string>Read the current node as a string.
Json.asI64
fn asI64(self): Option<i64>Read the current node as an integer.
Json.asF64
fn asF64(self): Option<f64>Read the current node as a float.
Json.asBool
fn asBool(self): Option<bool>Read the current node as a boolean.
Json.at
fn at(self, index: i64): Option<Json>Index into a JSON array.
Json.isNull
fn isNull(self): boolJson.isStr
fn isStr(self): boolJson.isNum
fn isNum(self): boolJson.isBool
fn isBool(self): boolJson.isArray
fn isArray(self): boolJson.isObject
fn isObject(self): boolJson.len
fn len(self): i64Length of an array or object.
Json.rawStr
fn rawStr(self): stringThe raw JSON text for this node.
Json.keys
fn keys(self): Vec<string>List all keys of an object.
Functions
Json.parse
fn Json.parse(s: string): Result<Json>Parse a JSON string. The returned Json borrows the input.
Example
from "std/json" import { Json }
from "std/io" import { writeStdout }
fn main(): i32 {
let data = Json.parse("{\"name\": \"milo\", \"version\": 1, \"tags\": [\"fast\", \"safe\"]}")!
match data.str("name") {
Some(name) => writeStdout(name),
None => writeStdout("unknown"),
}
let tags = data.get("tags")
match tags {
Some(arr) => {
let first = arr.at(0)
match first {
Some(tag) => {
match tag.asStr() {
Some(s) => writeStdout(s),
None => {},
}
},
None => {},
}
},
None => {},
}
return 0
}