json — parsing and writing JSON
mzs
include jsonINFO
Available in bot scripts.
| Function | What it does |
|---|---|
json.parse(s) | a JSON string → a value; a json error on broken input |
json.pretty(x) | a value → JSON indented by 2 spaces |
x.json | a value → compact JSON (a core method, no include needed) |
json(x) is an error: the module is not callable; the x.json method encodes.
Parsing
mzs
include json
order = json.parse('{"id": 7, "items": [{"sku": "A1", "qty": 2}], "note": null}')
order["items"][0]["sku"] # → "A1"
order["note"] # → nil
order.keys # → ["id","items","note"]Keys come in document order. A whole number is an int, the rest are float:
mzs
include json
json.parse("1.0") # → 1
json.parse("2.5") # → 2.5
type(json.parse("12345678901234567890")) # → "float"A deep path without errors: dig; a default value: ??:
mzs
include json
d = json.parse('{"user": {"name": "Ann"}}')
d.dig("user", "name") # → "Ann"
d.dig("user", "phone") ?? "none" # → "none"Writing
mzs
println({id: 7, tags: ["a", "b"], ok: true, x: nil}.json)
println([1.0, 2.5].json)
println((1..3).json)text
{"id":7,"tags":["a","b"],"ok":true,"x":null}
[1,2.5]
[1,2,3]mzs
include json
println(json.pretty({name: "Ann", tags: ["vip"]}))text
{
"name": "Ann",
"tags": [
"vip"
]
}- A whole
floatloses its.0; a range becomes an array. - Non-string keys are written as strings, a function as
null.
Round trip
mzs
include json
d = json.parse('{"z": 1, "a": [2, 3]}')
json.parse(d.json) == d # → trueErrors
mzs
include json
try json.parse("{oops") else (e) -> e["message"] # → "json.parse: invalid character 'o'"
try json.parse("") else (e) -> e["kind"] # → "json"
json.parse("null") # → nil
json.parse('{"a": 1} trailing') # → {"a":1}null is not an error but nil; text after a complete value is ignored. Nesting deeper than 256 levels is an error.
mzs
include json
json({a: 1})text
'json' is a module, not a function