Skip to content

json — разбор и запись JSON ​

mzs
include json

INFO

Доступен в скриптах ботов.

ФункцияЧто делает
json.parse(s)строка JSON → значение; ошибка json на кривом вводе
json.pretty(x)значение → JSON с отступом в 2 пробела
x.jsonзначение → компактный JSON (метод ядра, include не нужен)

json(x) — ошибка: модуль не вызывается, кодирует метод x.json.

Разобрать ​

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"]

Ключи идут в порядке документа. Целое число — int, остальные — float:

mzs
include json
json.parse("1.0")  # → 1
json.parse("2.5")  # → 2.5
type(json.parse("12345678901234567890"))  # → "float"

Глубокий путь без ошибок — dig, значение по умолчанию — ??:

mzs
include json
d = json.parse('{"user": {"name": "Аня"}}')
d.dig("user", "name")  # → "Аня"
d.dig("user", "phone") ?? "нет"  # → "нет"

Записать ​

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: "Аня", tags: ["vip"]}))
text
{
  "name": "Аня",
  "tags": [
    "vip"
  ]
}
  • Целый float теряет .0, диапазон становится массивом.
  • Не строковые ключи пишутся строками, функция — null.

Туда и обратно ​

mzs
include json
d = json.parse('{"z": 1, "a": [2, 3]}')
json.parse(d.json) == d  # → true

Ошибки ​

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} хвост')  # → {"a":1}

null — не ошибка, а nil; текст после целого значения игнорируется. Вложенность больше 256 уровней — ошибка.

mzs
include json
json({a: 1})
text
'json' is a module, not a function