json
JSON serialization and deserialization.
Types
| Type | Description |
|---|---|
DecodeError |
Raised when decode is given invalid JSON. |
EncodeError |
Raised when encode is given a value that can't be written as
JSON as it stands. |
DecodeValue |
A value decoded from JSON. |
EncodeValue |
A value that encodes as JSON. An object key may also be a number or boolean, which is written as its string form. |
DecodeValue
@let DecodeValue = $
| nil
| Bool
| Int
| Float
| Str
| Array[DecodeValue]
| Dict[Str, DecodeValue]
A value decoded from JSON.
EncodeValue
@let EncodeValue = $
| nil
| Bool
| Int
| Float
| Str
| Sym
| BaseArray[EncodeValue]
| Tuple[...EncodeValue]
| Record[...{*EncodeValue, **EncodeValue}]
| std.BaseStruct[{*EncodeValue, **EncodeValue}]
| BaseDict[Str | Sym | Int | Float | Bool, EncodeValue]
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 -> DecodeValue
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 that fits neither a signed nor an unsigned 64-bit integer decodes
as a Float.
Parameters
| Name | Type | Description |
|---|---|---|
json |
Str |
JSON string to parse. |
Errors
DecodeError if the JSON is invalid or text follows the
value.
Example
assert_eq (decode "null") nil
assert_eq (decode "42") 42
assert_eq (decode "[1, 2, 3]") [1, 2, 3]
let Dict(obj) = decode "{\"name\": \"Alice\", \"age\": 30}"
assert_eq $obj["name"] "Alice"
assert_eq $obj["age"] 30
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 |
Struct |
object |
Record |
object |
Object keys are written in the order the dict holds them. A non-finite
Float is written as null.
Parameters
| Name | Type | Description |
|---|---|---|
value |
EncodeValue |
The value to serialize. |
:indent? |
Int |
Spaces per level; one line when omitted. |
Errors
| Exception | Condition |
|---|---|
TypeError |
A value has no JSON form, such as a Bin, or a key is not a Str, Sym, Int, Float, or Bool. |
EncodeError |
The value contains itself, an Int is outside the signed 64-bit range, or a Float key is not finite. |
ValueError |
indent is negative. |