rontolisp:json-stringify
(rontolisp:json-stringify value)
Serializes a Lisp value into a JSON document string, following the defaults of
the com.inuoe.jzon library and inverting
rontolisp:json-parse: a hash table becomes an
object, a vector or list an array, and nil, t and the symbol null become
false, true and null. It is a lightweight subset of jzon, so a program can
switch to jzon without changing shape.
Switch to com.inuoe.jzon when you outgrow the subset: for its richer features
(pretty-printing, a streaming writer, a :replacer, custom serialization), or
to make the JSON code portable to other Common Lisp implementations —
com.inuoe.jzon is a standard library, while rontolisp:json-* runs only on
rontolisp.
Value mapping
| Lisp | JSON |
|---|---|
nil | false |
t | true |
the symbol null | null |
| integer, float | number |
| ratio | number (converted with float) |
| string | string (quote, backslash and control characters are escaped) |
| vector, list | array |
| hash table | object (a symbol key is down-cased unless it has a lower-case letter) |
CLOS instance (standard-object) | object (each slot name → its value, in definition order) |
| keyword, symbol, character | string |
Anything else (functions, streams, multidimensional arrays) signals an error.
A hash table and a CLOS instance both serialize as objects, so there are two
ways to build one — a hash table (often via
rontolisp:plist-hash-table) for dynamic keys,
and a class for a fixed shape. A slot may itself hold a hash table (a nested
object), a list or vector (an array), or another instance:
A value parsed from JSON round-trips structurally:
Limitations
nilserializes asfalseand the empty list isnil, so use#()(an empty vector) for an empty array and an empty hash table for an empty object{}.- A list is always an array — build a hash table for a JSON object (jzon dropped
alist/plist detection, and so does this subset).
rontolisp:plist-hash-tableturns a keyword property list, androntolisp:alist-hash-tablean association list, into that hash table. - Hash-table key order in the output is backend-specific (unspecified), like
maphash. - Non-ASCII characters are emitted verbatim (never
\uXXXX-escaped), which is valid JSON. - On the WASM backends a float with magnitude 2³¹ or larger cannot be serialized (the float formatter traps); see the WASM guide.
Backend support
Works on every backend and in every WASM mode (Preview 1 included), like
rontolisp:json-parse: the serializer is written
in rontolisp itself and is compiled into the program when used.