Overview
JSON, read into a tree: RFC 8259, one character at a time.
(import (text json))
(match (parse-json "{\"name\": \"http\", \"tags\": [\"net\", \"web\"]}")
((Ok (JsonObj m)) (map-try-ref m "name")) ; (Some (JsonStr "http"))
((Ok other) None)
((Err why) (println why) None))
A document is read into a Json, a union with a case for each
kind of JSON value. Reading a record straight from JSON, and writing one
as JSON, is (text json-codec)’s: its def/json-type declares
a record and the instances that convert it.
What is read. Exactly RFC 8259: one value, with whitespace
around it and nothing else after it. A byte order mark before the value is
skipped. There are no comments, no trailing commas, no single quotes and
no unquoted keys. A number may not have a leading zero, and needs digits
after its decimal point and its exponent. A control character in a string
has to be escaped, and a \u escape for a surrogate has to be one
half of a pair of them; the pair is read as one character. A document
is UTF-8, as RFC 8259 requires: bytes that are not are refused, at the
line and column where they are.
How it reads. Off the document’s bytes, a chunk at a time:
read-some from a port, or the string’s own bytes for
parse-json. Outside a string everything JSON says is ASCII, so a
byte is a character there; inside one, a character of several bytes is
checked and copied whole.
Numbers. A number without a fraction or an exponent is a
JsonInt, a long. One with either, or one too wide for a
long, is a JsonFloat. So 1 and 1.0 are
different values in the tree; (text json-codec) reads either into
a double, and only the first into an integer.
Objects. By default an object is a JsonObj, a
(Map string Json), so the order its keys were written in is not
kept. With #:objects 'fields it is a JsonFields, its keys
and values in an IArray of pairs, in the document’s order. That
is quicker to read, by a fifth to a third on documents of many objects,
and to walk; looking up a key in it is a walk over the fields, which
is as quick as a Map for a few fields and slower for many.
json-object-ref looks up a key in either kind. Either way, when a
key is written twice the last value wins, and a JsonFields has
each key once.
Which to read. 'fields is the better choice when the
tree is walked rather than searched: when it is written back, folded
over, or read into records with (text json-codec), which looks
up each of a record’s few fields once. It also keeps the keys in the
document’s order. 'map is the better choice when objects with
many keys are looked up by key, often. Finding a string key in a
JsonFields compares it with the keys in turn, about 3 ns each:
as quick as a Map up to about five keys, nearly three times as
slow at sixteen, and more than ten times as slow at a hundred, where a
Map takes about 10 ns at any size. A key that is not there is compared with all of
them.
Errors. A document that is not JSON is an Err saying
where and why: line 1, column 7: ']' does not begin a value. A
column is a character, so one outside the BMP is one column. Nothing is
raised. A document nested deeper than
json-max-depth is refused the same way rather than exhausting the
stack.
Writing. json->string and write-json write a
Json as text, and written does too. What they write reads
back as the same value: a JsonFloat always has a point or an
exponent, so 2.0 stays a float, and a double is written with the
fewest digits that read back as the same double. The keys of a
JsonObj are written in sorted order, because a Map does
not keep the order they were read in, so the same value always gives the
same text. A JsonFields is written in its own order, so a
document read with #:objects 'fields is written back with its
keys where they were.
See also: Json, parse-json, read-json
Reference
Types
Json
union ↑ Types
A JSON value.
JsonNull- null.
JsonBool- true or false.
JsonInt- A number with no fraction and no exponent that fits in a long.
JsonFloat- Any other number.
JsonStr- A string, its escapes resolved.
JsonArr- An array, in order, as an IArray. Build one from a vec with vec->iarray.
JsonObj- An object, by key. The order of the keys is not kept; a key written twice keeps its last value.
JsonFields- An object read with #:objects 'fields: its keys and values in the document's order, each key once, with its last value.
The two kinds of object are different values: a JsonObj and a
JsonFields with the same fields are not =.
See also: parse-json, json-object-ref, JsonObjects
JsonObjects
union ↑ Types
How a reader stores an object: #:objects’s value.
ObjectsAsMap- 'map, the default: a JsonObj, by key.
ObjectsAsFields- 'fields: a JsonFields, in the document's order. Quicker to read, and slower to look a key up in when there are many.
See also: Json, read-json, parse-json
Functions
json-object-ref
function ↑ Functions
(: json-object-ref (-> Json string (Option Json)))
(json-object-ref j key)
The value of a key in an object of either kind.
j- The object: a JsonObj or a JsonFields.
key- The key.
- returns
- Some value, or None when there is no such key or j is not an object.
(json-object-ref (match (parse-json "{\"a\": 1}" #:objects 'fields) ((Ok j) j) ((Err _) JsonNull)) "a")
;; (Some (JsonInt 1))
In a JsonObj this is map-try-ref. In a JsonFields
it is a walk over the fields, as quick as a Map for a few and
slower for many: for an object that is looked up in often, read it as
a JsonObj.
See also: Json
read-json
function ↑ Functions
(: read-json (-> InputPort (#:objects JsonObjects) (Result string Json)))
(read-json port #:objects 'map)
Reads one JSON document from a port.
port- The port. Everything left in it is read: one value, and only space after it.
#:objects- 'map, the default, to read objects as JsonObj; 'fields to read them as JsonFields.
- returns
- The value, or why the text is not JSON, with its line and column.
A byte order mark before the value is skipped and does not count as a column. On a bjoroutine the port is read without blocking the thread.
See also: parse-json
json->string
function ↑ Functions
(: json->string (-> Json (#:indent int) (#:ascii bool) string))
(json->string j #:indent 0 #:ascii #f)
JSON text for a value: compact, or indented.
j- The value.
#:indent- Spaces for each level. 0, the default, writes everything on one line.
#:ascii- When
#t, each character outside ASCII is written as a\uescape, and a character outside the BMP as a surrogate pair of them. - returns
- The text.
parse-jsonreads it back as the same value.
(json->string (JsonObj (map-set (map-set (map-empty) "b" (JsonInt 1)) "a" (JsonFloat 2.0))))
;; "{\"a\":2.0,\"b\":1}"
(json->string (JsonArr (vec->iarray [(JsonStr "knee") JsonNull])) #:indent 2)
;; "[\n \"knee\",\n null\n]"
", \\ and the control characters are escaped in a string,
as RFC 8259 requires. Nothing else is, unless #:ascii #t.
A JsonFloat that is NaN or infinite has no JSON form, and raises
ArgumentException: that is a mistake in the program that made it.
See also: write-json, parse-json
write-json
function ↑ Functions
(: write-json (-> OutputPort Json (#:indent int) (#:ascii bool) void))
(write-json port j #:indent 0 #:ascii #f)
Writes the text json->string gives to a port.
port- The port.
j- The value.
#:indent- As for
json->string. #:ascii- As for
json->string.
The text goes to the port in parts of about 32 KB as it is made, so a large value is never in memory as one string, and the start of it is out before the end is made. On a bjoroutine each part’s write suspends rather than blocking the thread.
A value that raises while it is written, such as a JsonFloat
that is not finite, can leave the parts before it on the port.
See also: json->string, read-json
parse-json
function ↑ Functions
(: parse-json (-> string (#:objects JsonObjects) (Result string Json)))
(parse-json text #:objects 'map)
Reads one JSON document from a string.
text- The document.
#:objects- 'map, the default, to read objects as JsonObj; 'fields to read them as JsonFields.
- returns
- The value, or why the text is not JSON, with its line and column.
(parse-json "[1, 2.5, null]") ; (Ok (JsonArr #iarray[(JsonInt 1) (JsonFloat 2.5) JsonNull]))
(parse-json "[1, 2,]") ; (Err "line 1, column 7: ']' does not begin a value")
See also: read-json