Grav v1.14.0

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.

grav
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)
}
Output
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 like doc["a"]["b"][0] are safe. Check with isNull() or has(key).
  • asString(), asInt() and the other asX() throw TypeError when the value is of another kind. getString(key, fallback) and the other getX methods 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. set replaces 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.parse throws ValueError with a line and column; Json.tryParse returns null instead. 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, so doc["user"].set("name", "Ada") changes doc. asArray() returns a new Array each time.

API

enum JsonKind

Values

  • JsonKind.Null
  • JsonKind.Bool
  • JsonKind.Number
  • JsonKind.String
  • JsonKind.Array
  • JsonKind.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 — Member key of an object; a null value when absent or not an object.
  • fn at(i: int) -> JsonValue — Element i of 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 member key.
  • fn kindOf(key: string) -> int — The kind of member key without 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 — Member key as an int, or fallback when it is missing or not a number.
  • fn getLong(key: string, fallback: long) -> long — Member key as a long, or fallback when it is missing or not a number.
  • fn getFloat(key: string, fallback: double) -> double — Member key as a double, or fallback when it is missing or not a number.
  • fn getBool(key: string, fallback: bool) -> bool — Member key as a bool, or fallback when it is missing or not a boolean.
  • fn set(key: string, value: JsonValue) -> JsonValue — Set member key of an object (replacing an existing one in place).
  • fn set(key: string, value: string) -> JsonValue — Sets member key to a string (adding it, or replacing its value); returns this object.
  • fn set(key: string, value: long) -> JsonValue — Sets member key to a number; returns this object.
  • fn set(key: string, value: double) -> JsonValue — Sets member key to a number; returns this object.
  • fn set(key: string, value: bool) -> JsonValue — Sets member key to 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 member key; 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 (indent spaces per level; 2 by default).
  • fn pretty(indent: int) -> string — Indented JSON text, indent spaces 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() -> bool
  • fn 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() -> bool
  • fn next() -> Entry<string, JsonValue>

Edit this page on GitHub