libstd/json

JSON in the spirit of Python's json module, with an object for every value. json_parse(text) and json_load(path) return a Json; its methods read it (get, at, get_str, get_int...), change it (set, push, remove) and write it back (dumps, dumps_indent, save). Object keys keep their order and numbers keep their exact text, so a file that is read and written back comes out the same.

#include <libstd/json>

Includes libstd/dict, libstd/string, libstd/type, libstd/list, libstd/file.

Example

#include <libstd/stdio>
#include <libstd/json>

doc = json_parse("{\"name\": \"tryc\", \"tags\": [\"lang\", 42]}")
if doc.is_error():
    print(doc.error, "\n")
    exit(1)

print(doc.get_str("name"), "\n")               // tryc
tags = doc.get("tags")

print(tags.len(), " ", tags.at_int(1), "\n")    // 2 42

tags.push("json")
doc.set("version", 2)
print(doc.dumps(), "\n")
tryc
2 42
{"name":"tryc","tags":["lang",42,"json"],"version":2}

Reading

get(key) and at(i) return the Json stored there; get_str, get_int, get_float and get_bool (at_str, at_int... for arrays) return the value directly. A missing key or an index out of range is not an error: get and at return a fresh null, get_str returns "" and get_int 0. has(key) tells whether the key is there; kind, kind_name() and is_string(), is_array()... what a value is.

Method calls cannot be chained: doc.get("a").get_str("b") does not compile. Go one level at a time, through a variable:

libri = doc.get("libri")
for i = 0; i < libri.len(); i++:
    libro = libri.at(i)
    print(libro.get_str("titolo"), " ", libro.get_int("anno"), "\n")

key_at(i) and at(i) walk an object in order. A number keeps the text it had in the file: get_int converts it (dropping any decimals), get_float parses it, is_int() is 1 when it has neither a . nor an exponent.

Writing

set(key, value) and push(values...) take a str, int, long, float, char or Json. The language has no separate boolean type (1 == 1 is an int), so true/false and null are written json_bool(b) and json_null(). Setting a key that exists changes its value in place; a new key goes at the end. A float is written the way print writes it, six decimals, without the trailing zeros; json_number("8.50") keeps an exact text. A Json put in two places is the same object in both, as in Python.

book = json_object()
book.set("title", "Il nome della rosa")
book.set("year", 1980)
book.set("price", json_number("12.90"))
book.set("tags", json_array("novel", "mystery"))
book.set("available", json_bool(1))
print(book.dumps_indent(4), "\n")
book.save("book.json", 4)

dumps() writes compact text, dumps_indent(n) one element per line, like json.dumps(v, indent=n). Characters outside ASCII are written as they are (UTF-8); json_ascii(text) turns them into \uXXXX escapes, like Python's default ensure_ascii.

Errors

json_parse and json_load never stop the program. On a text that is not JSON they return a value of kind JSON_ERROR: error says what is wrong and where (expected ':' after key at line 3, column 7), error_pos is the byte offset in the text. The parser follows RFC 8259: no trailing commas, no comments, no NaN, no raw control characters inside strings, at most JSON_MAX_DEPTH nested arrays and objects. Misusing the library stops the program with a message: set on something that is not an object, push on something that is not an array, a value of another type.

Memory

Every value is an object, and an arena allocation takes at least one block, 512 bytes by default (--block-size, see Compiler options). For large documents a smaller block cuts the memory several times: parsing a 5.4 MB file takes 361 MB with the default and 79 MB with --block-size 64, at the same speed.

Constants

NameValueMeaning
JSON_NULL0kind of null, also what get returns for a missing key
JSON_BOOL1kind of true/false
JSON_NUMBER2kind of a number
JSON_STRING3kind of a string
JSON_ARRAY4kind of an array
JSON_OBJECT5kind of an object
JSON_ERROR6kind of what json_parse/json_load return on a text that is not JSON
JSON_MAX_DEPTH1000nested arrays and objects json_parse accepts; beyond, an error instead of running out of stack
JSON_INDEX_MIN8keys above which an object builds a hash index, so get stays fast

Classes

class
Json

One JSON value. kind is one of the JSON_* constants; error and error_pos describe a JSON_ERROR. The other fields hold the value (flag a boolean, text a number's text or a string's decoded content, count/items/keys the elements, index the key index of a large object): read them if useful, change them through the methods.

    kind int
    flag int
    count int
    cap int
    text str
    error str
    error_pos long
    items ref[]
    keys str[]
    index str
    is_null &Json_is_null
    is_bool &Json_is_bool
    is_number &Json_is_number
    is_int &Json_is_int
    is_string &Json_is_string
    is_array &Json_is_array
    is_object &Json_is_object
    is_error &Json_is_error
    kind_name &Json_kind_name
    len &Json_len
    has &Json_has
    get &Json_get
    at &Json_at
    key_at &Json_key_at
    as_str &Json_as_str
    as_int &Json_as_int
    as_float &Json_as_float
    as_bool &Json_as_bool
    get_str &Json_get_str
    get_int &Json_get_int
    get_float &Json_get_float
    get_bool &Json_get_bool
    at_str &Json_at_str
    at_int &Json_at_int
    at_float &Json_at_float
    at_bool &Json_at_bool
    set &Json_set
    push &Json_push
    remove &Json_remove
    remove_at &Json_remove_at
    dumps &Json_dumps
    dumps_indent &Json_dumps_indent
    save &Json_save
class
JsonParser

Parser state (text, position, depth, first error); created internally by json_parse.

    src str
    pos long
    len long
    depth int
    ok int
    error str
    error_pos long

Functions

def json_null() -> Json

A new null.

def json_bool(b: int) -> Json

A new true (any non-zero b) or false.

def json_int(n: long) -> Json

A new number from a long.

def json_float(x: float) -> Json

A new number from a float, written like print (six decimals, rounded) without the trailing zeros: 8.5 stays 8.5, 1e-9 becomes 0. NaN and infinity, which JSON lacks, give null.

def json_str(s: str) -> Json

A new string; the content is plain text, dumps adds the escapes.

def json_object() -> Json

A new empty object, to fill with set.

def json_array(*items) -> Json

A new array with the given values in order (json_array() is empty): str, int, long, float, char or Json.

def Json_is_null(self: Json) -> int
j.is_null(): 1 for null, including the one get returns for a missing key.
def Json_is_bool(self: Json) -> int
j.is_bool(): 1 for true/false.
def Json_is_number(self: Json) -> int
j.is_number(): 1 for a number.
def Json_is_int(self: Json) -> int
j.is_int(): 1 for a number with neither . nor an exponent, which as_int reads exactly.
def Json_is_string(self: Json) -> int
j.is_string(): 1 for a string.
def Json_is_array(self: Json) -> int
j.is_array(): 1 for an array.
def Json_is_object(self: Json) -> int
j.is_object(): 1 for an object.
def Json_is_error(self: Json) -> int
j.is_error(): 1 for what json_parse/json_load return on a text that is not JSON (see error).
def Json_kind_name(self: Json) -> str
j.kind_name(): "null", "bool", "number", "string", "array", "object" or "error".
def Json_len(self: Json) -> int
j.len(): elements of an array, keys of an object, bytes of a string; 0 otherwise.
def Json_has(self: Json, key: str) -> int
j.has(key): 1 if the object has the key.
def Json_get(self: Json, key: str) -> Json
j.get(key): the value of key; a fresh null if there is none (or j is not an object).
def Json_at(self: Json, i: int) -> Json
j.at(i): element i of an array, or the value at position i of an object; a fresh null out of range.
def Json_key_at(self: Json, i: int) -> str
j.key_at(i): the key at position i of an object, "" out of range.
def Json_as_str(self: Json) -> str
j.as_str(): a string's content, a number's text, "true"/"false"; "" for anything else.
def Json_as_int(self: Json) -> long
j.as_int(): a number as a long (decimals dropped, clamped to 64 bits), a boolean as 0/1, the leading digits of a string; 0 otherwise.
def Json_as_float(self: Json) -> float
j.as_float(): a number (or a string holding one) as a float, a boolean as 0.0/1.0; 0.0 otherwise.
def Json_as_bool(self: Json) -> int
j.as_bool(): Python's truth: false, 0, "", [], {} and null are 0, the rest 1.
def Json_get_str(self: Json, key: str) -> str
j.get_str(key): get(key).as_str(), "" for a missing key.
def Json_get_int(self: Json, key: str) -> long
j.get_int(key): get(key).as_int(), 0 for a missing key.
def Json_get_float(self: Json, key: str) -> float
j.get_float(key): get(key).as_float(), 0.0 for a missing key.
def Json_get_bool(self: Json, key: str) -> int
j.get_bool(key): get(key).as_bool(), 0 for a missing key.
def Json_at_str(self: Json, i: int) -> str
j.at_str(i): at(i).as_str().
def Json_at_int(self: Json, i: int) -> long
j.at_int(i): at(i).as_int().
def Json_at_float(self: Json, i: int) -> float
j.at_float(i): at(i).as_float().
def Json_at_bool(self: Json, i: int) -> int
j.at_bool(i): at(i).as_bool().
def Json_set(self: Json, key: str, *value) -> None
j.set(key, value): in an object, sets key to one value (str, int, long, float, char or Json). An existing key keeps its position, a new one goes at the end.
def Json_push(self: Json, *values) -> None
j.push(values...): appends the values to an array, in order.
def Json_remove_at(self: Json, i: int) -> int
j.remove_at(i): removes element i of an array (or the entry at position i of an object); the later ones move down. 1 if removed.
def Json_remove(self: Json, key: str) -> int
j.remove(key): removes key from an object; 1 if it was there.
def json_quote(s: str) -> str
s as a quoted JSON string: ", \ and control characters become escapes, the rest (UTF-8 included) stays as it is.
def Json_dumps(self: Json) -> str
j.dumps(): compact JSON text, without spaces (an error is written as null).
def Json_dumps_indent(self: Json, indent: int) -> str
j.dumps_indent(n): one element per line and n spaces per level, like json.dumps(v, indent=n); 0 gives the compact text.
def json_ascii(text: str) -> str

The text with every character outside ASCII written as \uXXXX (a surrogate pair above U+FFFF), like Python's ensure_ascii. Applied to JSON text the result is still valid JSON.

def Json_save(self: Json, path: str, indent: int) -> int
j.save(path, indent): writes dumps_indent(indent) and a newline to a file, created or replaced. 1 if written, 0 if the file cannot be opened or written.
def json_parse(text: str) -> Json

Parses a JSON text, like json.loads. On a text that is not JSON, a JSON_ERROR with error (what and where) and error_pos (byte offset).

def json_number(text: str) -> Json

A new number from its exact text ("8.50", "1e-9"), written back as it is. A text that is not a JSON number stops the program with a message.

def json_load(path: str) -> Json

Reads and parses a JSON file, like json.load; a JSON_ERROR if the file cannot be read or is not JSON.

Internal helpers

Used by the functions above; not meant to be called directly.