Pelago
stdText and data formats

std.json

Parse and write JSON.

import std.json

json.parse(text) returns a json.value ! parse_error. A value is one of:

CaseHolds
nothingJSON null.
flag(value)A boolean.
number(value)A float. All JSON numbers are floats.
text(value)A string.
items(values)An array.
fields(keys, values)An object. Keys keep the order they were written in.

Methods on a value:

MethodResultNotes
get(key)value?A field of an object.
at(i)value?An element of an array.
size()intNumber of elements or fields.
asNumber(), asText(), asBool()float?, string?, bool?The content when the value has that kind.
encode()stringCompact JSON text.
pretty(indent)stringIndented JSON text; indent defaults to 2.
import std.json

fn main() {
    switch json.parse("{\"name\": \"Pelago\", \"tags\": [1, 2]}") {
        case ok(doc):
            print(doc.encode())
            const tags = doc.get("tags") ?? json.value.nothing
            print("#(tags.size()) tags, second is #((tags.at(1) ?? json.value.nothing).asNumber() ?? 0.0)")
        case err(e): print("bad: #(e.message)")
    }
    switch json.parse("{oops") {
        case ok(_): print("unexpected")
        case err(e): print("bad: #(e.message)")
    }
}
{"name":"Pelago","tags":[1,2]}
2 tags, second is 2
bad: a key must be a string

Typed decoding and encoding

For data with a known shape, describe it as a struct or enum and let the compiler write the code with @derive(fromJson) and @derive(toJson). That has its own page: Typed JSON, which also covers renaming fields and strict mode.

On this page