ilusm.dev

jsn

JSON convenience wrapper - encode a value to a JSON string, decode a JSON string to an ilusm value, safely try-parse without throwing, get a field from a decoded object without crashing on missing keys, and list an object's keys. A thin, ergonomic facade over the json module.

Load with: use jsn

What this module does

jsn exposes json.enc and json.dec under the shorter names jsnen / jsnde, and adds two safety helpers: jsntr wraps decoding in a try so a malformed string returns an {err} envelope instead of crashing, and jsnge safely retrieves a key from a decoded object returning nil instead of erroring on missing fields.

All functions are also available via the jsn namespace object.

Quick example

use jsn

# Encode
s = jsnen({name: "alice", age: 30})
# '{"name":"alice","age":30}'

# Decode
obj = jsnde(s)
prn(obj.name)  # "alice"

# Safe parse (won't throw on bad input)
r = jsntr("not json")
if r.err != nil:
    prn("parse error")

# Safe field get
val = jsnge(obj, "missing")  # nil instead of error

# Keys
ks = jsnke(obj)  # ["name", "age"]

# Namespace style
prn(jsn.enc({x: 1}))
prn(jsn.get(obj, "name"))

Functions

Encoding and decoding

jsnen(v) / jsn.enc(v)

Encodes any ilusm value to a JSON string via json.enc.

jsnde(s) / jsn.dec(s)

Decodes a JSON string to an ilusm value via json.dec. Throws on parse errors.

jsntr(raw) / jsn.try_parse(raw)

Safely tries to decode raw (coerced to string) as JSON. Returns {val, err} - on success err is nil, on failure val is nil and err carries the error. Does not throw.

Object helpers

jsnge(obj, key) / jsn.get(obj, key)

Gets field key from obj. Returns nil if the field is absent instead of throwing. Errors if obj is not an object.

jsnke(obj) / jsn.keys(obj)

Returns the list of keys in obj via okeys. Errors if obj is not an object.

Notes

  • For the full pure-ilusm JSON encoder/decoder (string escaping, number parsing, nested arrays and objects), see the json module.
  • Requires json.