(rontolisp) docs
← rontolisp Package Functions

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

LispJSON
nilfalse
ttrue
the symbol nullnull
integer, floatnumber (an integer in decimal, whatever *print-base* is)
rationumber (converted with float)
stringstring (quote, backslash and control characters are escaped)
vector, listarray
hash tableobject (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, characterstring

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

  • nil serializes as false and the empty list is nil, 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-table turns a keyword property list, and rontolisp:alist-hash-table an association list, into that hash table.
  • A hash table's members come out in the order their keys were first stored, on every backend, 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.
  • On the wasm-GC backends the string it answers is immutable, as a string literal is (see rontolisp:json-parse).

Backend support

Works on every backend and in every WASM mode (Preview 1 included), like rontolisp:json-parse: the interpreter and the JVM run a serializer written in rontolisp itself, and the wasm-GC backends compile a native one into the program when it is used.