JSON

std.json, a recursive Json enum with a hand-written parser and serialiser, and the string-literal rule you need to use it.

vlatest

std.json is a small, self-contained JSON implementation. It models a document as a recursive enum and ships its own parser and serialiser.

Write object documents with a triple-quoted string

Before anything else, one rule. In a normal string literal, { always opens an interpolation, and \{ is the only way to get a literal brace. That makes the obvious spelling of a JSON object wrong:

let text = "{"name": "ada"}"   // broken

Escape the brace, and use a triple-quoted string so the inner " characters do not have to be escaped:

import { parse, typeOf, field, asStr } from std.json

fn main() {
    let text = """\{"name": "ada", "age": 36}"""
    match (parse(text)) {
        case some(doc) -> { println(typeOf(doc)) }
        case none -> { println("invalid JSON") }
    }
}

A triple-quoted string ends only at """, so a single " inside it is an ordinary character, you only need \{ for the opening brace. Inline arrays need neither:

import { parse, typeOf } from std.json

fn main() {
    match (parse("""[1, 2, 3]""")) {
        case some(d) -> { println(typeOf(d)) }
        case none -> { println("invalid") }
    }
}

See Strings for the full literal rules.

The Json enum

The variants are prefixed with J, and pattern matching is written with the enum name in front:

Variant Carries typeOf returns
Json.JNull , "null"
Json.JBool bool "bool"
Json.JNum float "number"
Json.JStr string "string"
Json.JArr List<Json> "array"
Json.JObj List<(string, Json)> "object"

The typeOf strings are lowercase, and the numeric case is "number", not "num".

Parsing and serialising

Function Signature
parse parse(text: string) -> Json?
stringify stringify(v: Json) -> string

parse returns none on malformed input rather than raising anything, and stringify emits compact JSON with no spaces. Do not rely on object key order it follows the parser's internal map, not your source text.

import { parse, stringify } from std.json

fn main() {
    match (parse("""\{"a": [1, 2], "b": null}""")) {
        case some(doc) -> { println(stringify(doc)) }
        case none -> { println("invalid") }
    }
}

Reading values

Function Signature Returns
typeOf typeOf(v: Json) -> string the lowercase tag
asBool asBool(v: Json) -> bool? the value, or none
asNum asNum(v: Json) -> float? the value, or none
asStr asStr(v: Json) -> string? the value, or none
field field(v: Json, key: string) -> Json? the member, or none

Every accessor returns an optional, and none means "wrong type" or "no such key", there is no way to tell those apart. field only works on a Json.JObj.

import { parse, typeOf, field, asStr, asNum } from std.json

fn main() {
    let text = """\{"name": "ada", "age": 36}"""
    match (parse(text)) {
        case some(doc) -> {
            println(typeOf(doc))
            match (field(doc, "name")) {
                case some(v) -> {
                    match (asStr(v)) {
                        case some(s) -> { println("name {s}") }
                        case none -> { println("name is not a string") }
                    }
                }
                case none -> { println("no name key") }
            }
            match (field(doc, "age")) {
                case some(v) -> {
                    match (asNum(v)) {
                        case some(n) -> { println("age {n}") }
                        case none -> {}
                    }
                }
                case none -> {}
            }
        }
        case none -> { println("invalid JSON") }
    }
}

Walking a document

Because Json is an ordinary enum, match is the idiomatic way to walk it. Destructure a tuple element directly in the for header.

import { Json, parse } from std.json

fn countScalars(v: Json) -> int {
    match (v) {
        case Json.JNull -> { return 0 }
        case Json.JBool(b) -> { return 1 }
        case Json.JNum(n) -> { return 1 }
        case Json.JStr(s) -> { return 1 }
        case Json.JArr(items) -> {
            var n = 0
            for (item in items) {
                n += countScalars(item)
            }
            return n
        }
        case Json.JObj(fields) -> {
            var n = 0
            for ((key, value) in fields) {
                n += countScalars(value)
            }
            return n
        }
    }
}

fn main() {
    match (parse("""\{"a": 1, "b": ["x", "y"]}""")) {
        case some(doc) -> { println("scalars {countScalars(doc)}") }
        case none -> { println("invalid JSON") }
    }
}

Note the case Json.JBool(b) -> form: a unit variant is written bare, and a payload variant carries the payload in parentheses. The bindings are only needed if you use them.

The Parser class

Parser is exported, but parse is a thin wrapper that returns the optional directly and is what you want:

Member Signature
constructor constructor(text: string)
parseValue parseValue() -> Json?
peek peek() -> int
next next() -> int
skipWs skipWs()

Next steps