JSON
import "std/data" (included in import "std") · namespace std.data
Reading, building and writing JSON. Json.parse turns text into a JsonValue, a tree you can walk; Json.object() and Json.array() start new values you build with set and push; toJson() and pretty() turn a value back into text.
import "std"
fn main() {
let doc = Json.parse("{\"name\": \"grav\", \"tags\": [\"fast\", \"small\"], \"stars\": 42}")
print(doc["name"].asString())
print(doc["tags"][1].asString())
print(doc.getInt("stars", 0))
print(doc["owner"]["login"].isNull())
print(doc.path("tags.0").asString())
for (t in doc["tags"].asArray()) { print("tag: ${t.asString()}") }
let out = Json.object()
.set("ok", true)
.set("count", 3 as long)
.set("items", Json.array().push("a").push(1.5))
print(out.toJson())
print(out.pretty())
try {
Json.parse("{\"a\": }")
} catch (e: ValueError) {
print(e.message())
}
print(Json.tryParse("not json") == null)
}grav
small
42
true
fast
tag: fast
tag: small
{"ok":true,"count":3,"items":["a",1.5]}
{
"ok": true,
"count": 3,
"items": [
"a",
1.5
]
}
JSON parse error at line 1, column 7: unexpected character
true- Lookups never fail. A missing key or index gives a JSON
null, so chains likedoc["a"]["b"][0]are safe. Check withisNull()orhas(key). asString(),asInt()and the otherasX()throwTypeErrorwhen the value is of another kind.getString(key, fallback)and the othergetXmethods return the fallback instead.path("a.b.0")follows a dotted path of keys and indexes.- Numbers: integers are kept exactly as 64-bit values (
asLong()); other numbers are doubles. - Objects keep insertion order.
setreplaces an existing key in place;remove(key)deletes one. ==compares structure; the order of object keys does not matter.- Repeated keys: the last value wins, at the first key's place (as in JavaScript's
JSON.parse).kindOf(key)tells a member's kind without making a value for it (-1 when missing, 6 for an integer). - Speed: the parser reads members straight into the compact storage in C: about 1.3 µs for a 9-field object and 0.9 ms for 250 KB (about 280 MB/s). To read JSON straight into your own classes, see JsonMap.
Json.parsethrowsValueErrorwith a line and column;Json.tryParsereturnsnullinstead.Json.quote(s)escapes a string as a JSON literal.- Storage is compact. Arrays and objects keep their numbers, booleans and strings inline (16 bytes each, plus the text of strings), and the parser shares repeated keys, so 100,000 three-field records take about 20 MB. Reading a scalar gives a fresh
JsonValue; nested arrays and objects are shared, sodoc["user"].set("name", "Ada")changesdoc.asArray()returns a newArrayeach time.
API
enum JsonKind
Values
JsonKind.NullJsonKind.BoolJsonKind.NumberJsonKind.StringJsonKind.ArrayJsonKind.Object
class JsonValue
One JSON value: null, a boolean, a number, a string, an array, or an object. Arrays and objects store their elements compactly; reading a number, string or boolean out of one gives a fresh JsonValue (scalars cannot be changed anyway).
Constructors
new JsonValue()new JsonValue(kind: JsonKind)— A new empty value of the given kind (null, false, 0, "", [], {}).
Static members
static fn ofKind(kind: JsonKind) -> JsonValue— A new empty value of the given kind (null, false, 0, "", [], {}).static fn ofBool(b: bool) -> JsonValue— A JSON boolean.static fn ofInt(n: long) -> JsonValue— A JSON number holding an integer.static fn ofFloat(d: double) -> JsonValue— A JSON number.static fn ofString(s: string) -> JsonValue— A JSON string.
Methods
fn kind() -> JsonKind— What kind of value this is (Null, Bool, Number, String, Array, Object).fn isNull() -> bool— Whether this is null.fn isBool() -> bool— Whether this is true or false.fn isNumber() -> bool— Whether this is a number.fn isInteger() -> bool— A number with no fractional part that fits in a long.fn isString() -> bool— Whether this is a string.fn isArray() -> bool— Whether this is an array.fn isObject() -> bool— Whether this is an object.fn asBool() -> bool— The boolean (TypeError when this is not a boolean).fn asFloat() -> double— The number as a double (TypeError when this is not a number).fn asLong() -> long— The number as a long, fraction dropped (TypeError when this is not a number).fn asInt() -> int— The number as an int (TypeError when this is not a number).fn asString() -> string— The string (TypeError when this is not a string).fn asArray() -> Array<JsonValue>— The elements, as a new Array (TypeError when this is not an array). Nested arrays and objects in it are shared with this one.fn size() -> int— Elements of an array or members of an object (0 for anything else).fn length() -> int— The number of elements or members (same as size()).fn isEmpty() -> bool— Whether an array or object has nothing in it.fn get(key: string) -> JsonValue— Memberkeyof an object; a null value when absent or not an object.fn at(i: int) -> JsonValue— Elementiof an array; a null value when out of range or not an array.fn operator[](key: string) -> JsonValue—v["key"]: member key of an object (null when absent).fn operator[](i: int) -> JsonValue—v[i]: element i of an array.fn has(key: string) -> bool— Whether an object has memberkey.fn kindOf(key: string) -> int— The kind of memberkeywithout making a value for it: -1 when there is none, else JsonKind's number (0 null, 1 bool, 2 number, 3 string, 4 array, 5 object), with 6 for a number holding an integer.fn iterator() -> JsonItems— An array's elements, or an object's member values, one at a time:for (item in json["items"]).fn entries() -> JsonEntries— An object's members as key and value, in insertion order:for ((key, value) in obj.entries())(nothing for anything but an object).fn keys() -> Array<string>— An object's keys, in insertion order.fn path(dotted: string) -> JsonValue— A path through nested objects and arrays: "server.ports.0".fn getString(key: string, fallback: string) -> string— Lookups with a fallback (when absent or of another type).fn getInt(key: string, fallback: int) -> int— Memberkeyas an int, orfallbackwhen it is missing or not a number.fn getLong(key: string, fallback: long) -> long— Memberkeyas a long, orfallbackwhen it is missing or not a number.fn getFloat(key: string, fallback: double) -> double— Memberkeyas a double, orfallbackwhen it is missing or not a number.fn getBool(key: string, fallback: bool) -> bool— Memberkeyas a bool, orfallbackwhen it is missing or not a boolean.fn set(key: string, value: JsonValue) -> JsonValue— Set memberkeyof an object (replacing an existing one in place).fn set(key: string, value: string) -> JsonValue— Sets memberkeyto a string (adding it, or replacing its value); returns this object.fn set(key: string, value: long) -> JsonValue— Sets memberkeyto a number; returns this object.fn set(key: string, value: double) -> JsonValue— Sets memberkeyto a number; returns this object.fn set(key: string, value: bool) -> JsonValue— Sets memberkeyto a boolean; returns this object.fn operator[]=(key: string, value: JsonValue)—v["key"] = value: sets member key of an object.fn remove(key: string) -> bool— Removes memberkey; whether it was there.fn push(value: JsonValue) -> JsonValue— Append to an array.fn push(value: string) -> JsonValue— Appends a string to an array; returns this array.fn push(value: long) -> JsonValue— Appends a number to an array; returns this array.fn push(value: double) -> JsonValue— Appends a number to an array; returns this array.fn push(value: bool) -> JsonValue— Appends a boolean to an array; returns this array.fn toJson() -> string— Compact JSON text.fn pretty() -> string— Indented JSON text (indentspaces per level; 2 by default).fn pretty(indent: int) -> string— Indented JSON text,indentspaces per level.fn toString() -> string— The compact JSON text (same as toJson()).fn operator==(other: JsonValue) -> bool— Structural equality (object member order does not matter).
class JsonParser
The recursive-descent parser behind Json.parse. It writes scalars straight into the containers it builds, without a JsonValue per number or string.
Constructors
new JsonParser(src: string)
Methods
fn document() -> JsonValue— Parses the whole input as one JSON value (ValueError on bad input or trailing text).
class Json
Entry points: parsing and building values.
Static members
static fn parse(text: string) -> JsonValue— Parse JSON text; throws ValueError (with line and column) when invalid.static fn tryParse(text: string) -> JsonValue— Parse, or return null when the text is not valid JSON.static fn stringify(v: JsonValue) -> string— The compact JSON text of a value.static fn object() -> JsonValue— A new empty JSON object {}.static fn array() -> JsonValue— A new empty JSON array [].static fn nil() -> JsonValue— The JSON null value.static fn of(b: bool) -> JsonValue— A JSON boolean.static fn of(n: long) -> JsonValue— A JSON number holding an integer.static fn of(d: double) -> JsonValue— A JSON number.static fn of(s: string) -> JsonValue— A JSON string.static fn strings(xs: Array<string>) -> JsonValue— A JSON array of strings.static fn quote(s: string) -> string— Quote a string as a JSON string literal.
class JsonItems implements Iterator<JsonValue>
An array's elements or an object's member values, in order (see JsonValue.iterator).
Constructors
new JsonItems(v: JsonValue)
Methods
fn hasNext() -> boolfn next() -> JsonValue
class JsonEntries implements Iterator<Entry<string, JsonValue>>
An object's members as Entry(key, value), in order (see JsonValue.entries).
Constructors
new JsonEntries(v: JsonValue)
Methods
fn hasNext() -> boolfn next() -> Entry<string, JsonValue>