Skip to content

json

JSON serialization and deserialization.

Types

TypeDescription
Data A value decoded from JSON.
Encodable A value that encodes as JSON. An object key may also be a number or boolean, which is written as its string form.

Data = (nil | Bool | Int | Float | Str | Array[Data] | Dict[Str, Data])

A value decoded from JSON.

Encodable = (nil | Bool | Int | Float | Str | Sym | Array[Encodable] | Tuple[...Encodable] | Record[...{...Encodable, ...Sym: Encodable}] | Dict[Str | Sym | Int | Float | Bool, Encodable])

A value that encodes as JSON. An object key may also be a number or boolean, which is written as its string form.

Functions

decode json -> Data

Deserializes a JSON string to a Do value.

JSON Type Do Type
null nil
boolean Bool
integer Int
float Float
string Str
array Array
object Dict

An integer too large for Int decodes as a Float.

Parameters

NameTypeDescription
json Str JSON string to parse.

Errors

ValueError if the JSON is invalid.

Example

assert_eq (decode "null") nil
assert_eq (decode "42") 42
assert_eq (decode "[1, 2, 3]") [1, 2, 3]

let obj = decode "{\"name\": \"Alice\", \"age\": 30}"
assert_eq $obj["name"] "Alice"
assert_eq $obj["age"] 30
Open in playground

encode value … -> Str

Serializes a Do value to a JSON string.

Do Type JSON Type
nil null
Bool boolean
Int number
Float number
Str string
Sym string (symbol name)
Array array
Tuple array
Dict object
Record object

Object keys are written in the order the dict holds them.

Parameters

NameTypeDescription
value Encodable The value to serialize.
:indent? Int Spaces per level; one line when omitted.

Example

assert_eq (encode 42) "42"
assert_eq (encode "hello") "\"hello\""
assert_eq (encode nil) "null"
assert_eq (encode [1, 2] indent: 2) "[\n  1,\n  2\n]"