ilusm.dev
Guide

Working with JSON

The jsn module handles JSON encoding and decoding. Two functions - that's all you need.

The basics

use jsn

# Decode: JSON string → ilusm value
data = jsn.dec('{"name": "ibot", "port": 8080}')
prn data.name   # "ibot"
prn data.port   # 8080

# Encode: ilusm value → JSON string
obj = {name: "ibot", tags: ["fast", "small"]}
prn jsn.enc(obj)
# {"name":"ibot","tags":["fast","small"]}

JSON ↔ ilusm type mapping

JSONilusm type
stringstr
numbernum
booleanbol (tru/fls)
nullnil
arraylst
objectobj

Reading a JSON file

use fs
use jsn

cfg = jsn.dec(fs.rd("config.json"))
prn cfg.host
prn cfg.port or 8080

Writing a JSON file

use fs
use jsn

data = {users: ["alice", "bob"], count: 2}
fs.wr("output.json", jsn.enc(data))

Working with API responses

use net
use jsn

res = net.get("https://api.example.com/users")
if res.cod != 200:
    err($"API error: {res.cod}")

users = jsn.dec(res.txt)
u <- users:
    prn $"{u.name} - {u.email}"

Sending JSON in a POST request

use net
use jsn

body = jsn.enc({username: "ibot", action: "login"})
res  = net.post("https://api.example.com/auth", body)
prn res.cod   # 200

Handling decode errors safely

jsn.dec raises on invalid JSON. Use try or jsn.try_parse to handle bad input:

use jsn

# Using try
raw = "not valid json {"
r = try(\() jsn.dec(raw))
if r.err:
    prn $"bad JSON: {r.err}"
| prn r.val

# Using jsn.try_parse - returns {val, err} directly
r2 = jsn.try_parse(raw)
if r2.err:
    prn "parse failed"
| prn r2.val

Nested JSON

use jsn

raw = '{"user": {"name": "ibot", "roles": ["admin", "user"]}}'
data = jsn.dec(raw)

prn data.user.name        # "ibot"
prn data.user.roles[0]    # "admin"
prn len(data.user.roles)  # 2