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
| Name | Value | Meaning |
|---|---|---|
JSON_NULL | 0 | kind of null, also what get returns for a missing key |
JSON_BOOL | 1 | kind of true/false |
JSON_NUMBER | 2 | kind of a number |
JSON_STRING | 3 | kind of a string |
JSON_ARRAY | 4 | kind of an array |
JSON_OBJECT | 5 | kind of an object |
JSON_ERROR | 6 | kind of what json_parse/json_load return on a text that is not JSON |
JSON_MAX_DEPTH | 1000 | nested arrays and objects json_parse accepts; beyond, an error instead of running out of stack |
JSON_INDEX_MIN | 8 | keys above which an object builds a hash index, so get stays fast |
Classes
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_saveParser 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 longFunctions
A new null.
A new true (any non-zero b) or false.
A new number from a long.
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.
A new string; the content is plain text, dumps adds the escapes.
A new empty object, to fill with set.
A new array with the given values in order (json_array() is empty): str, int, long, float, char or Json.
j.is_null(): 1 for null, including the one get returns for a missing key.j.is_bool(): 1 for true/false.j.is_number(): 1 for a number.j.is_int(): 1 for a number with neither . nor an exponent, which as_int reads exactly.j.is_string(): 1 for a string.j.is_array(): 1 for an array.j.is_object(): 1 for an object.j.is_error(): 1 for what json_parse/json_load return on a text that is not JSON (see error).j.kind_name(): "null", "bool", "number", "string", "array", "object" or "error".j.len(): elements of an array, keys of an object, bytes of a string; 0 otherwise.j.has(key): 1 if the object has the key.j.get(key): the value of key; a fresh null if there is none (or j is not an object).j.at(i): element i of an array, or the value at position i of an object; a fresh null out of range.j.key_at(i): the key at position i of an object, "" out of range.j.as_str(): a string's content, a number's text, "true"/"false"; "" for anything else.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.j.as_float(): a number (or a string holding one) as a float, a boolean as 0.0/1.0; 0.0 otherwise.j.as_bool(): Python's truth: false, 0, "", [], {} and null are 0, the rest 1.j.get_str(key): get(key).as_str(), "" for a missing key.j.get_int(key): get(key).as_int(), 0 for a missing key.j.get_float(key): get(key).as_float(), 0.0 for a missing key.j.get_bool(key): get(key).as_bool(), 0 for a missing key.j.at_str(i): at(i).as_str().j.at_int(i): at(i).as_int().j.at_float(i): at(i).as_float().j.at_bool(i): at(i).as_bool().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.j.push(values...): appends the values to an array, in order.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.j.remove(key): removes key from an object; 1 if it was there.s as a quoted JSON string: ", \ and control characters become escapes, the rest (UTF-8 included) stays as it is.j.dumps(): compact JSON text, without spaces (an error is written as null).j.dumps_indent(n): one element per line and n spaces per level, like json.dumps(v, indent=n); 0 gives the compact text.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.
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.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).
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.
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.
- def json_new(kind: int) -> Json
- def json_float_text(x: float) -> str
- def json_misuse(where: str, what: str) -> None
- def json_value_of(v: Vararg, where: str) -> Json
- def json_reserve(j: Json) -> None
- def json_append(a: Json, v: Json) -> None
- def json_index_build(obj: Json) -> None
- def json_find(obj: Json, key: str) -> int
- def json_put(obj: Json, key: str, v: Json) -> None
- def json_text_is_int(t: str) -> int
- def json_spaces(n: int) -> str
- def json_write(v: Json, indent: int, level: int) -> str
- def jp_new(text: str) -> JsonParser
- def jp_fail(p: JsonParser, msg: str, pos: long) -> None
- def jp_peek(p: JsonParser) -> char
- def jp_skip_ws(p: JsonParser) -> None
- def jp_enter(p: JsonParser) -> int
- def jp_word(p: JsonParser, word: str) -> int
- def jp_digits(p: JsonParser) -> int
- def jp_number(p: JsonParser) -> Json
- def jp_hex4(p: JsonParser, pos: long) -> int
- def json_utf8_encode_into(buf: str, pos: long, codepoint: int) -> long
- def jp_string(p: JsonParser) -> str
- def jp_array(p: JsonParser) -> Json
- def jp_object(p: JsonParser) -> Json
- def jp_value(p: JsonParser) -> Json
- def json_error_at(src: str, msg: str, pos: long) -> Json