Skip to content

std::json

JSON text to and from Nomi values. Json.decode_as<T> reads text as a typed value and Json.encode_as writes one. A struct takes part with derive ToJson and derive FromJson, and the built-in types and collections already do. Json.decode and Json.encode work with the Json tree itself, for JSON whose shape is not known in advance.

Import with import std::json.

enum Json
    String String
    Int Int
    Float Float
    Bool Bool
    Arr List<Json>
    Obj Map<String, Json>
    Null
end

A parsed JSON value. Each variant is named after the Nomi type it holds (String, Int, Float, Bool), so a pattern such as Json.Int(n) says what n is. Arr holds an array, Obj an object and Null is JSON’s null.

JSON has one number type. Json.decode reads a number with no decimal point and no exponent as Int, exactly and at any length, and any other number as Float. The split does not survive a round trip through text: Json.encode(Json.Float(36.0)) writes 36, which decodes as Json.Int(36).

assert Json.decode("36") == Result.Ok(Json.Int(36))
assert Json.decode("36.5") == Result.Ok(Json.Float(36.5))
assert Json.decode("1e2") == Result.Ok(Json.Float(100.0))
assert Json.encode(Json.Float(36.0)) == "36"

label = case Json.decode("[1, null]")
    .Ok(Json.Arr(items)) -> "an array of ${Iter.count(items)}"
    .Ok(_)               -> "something else"
    .Err(_)              -> "not JSON"
end

assert label == "an array of 2"
fn decode(source: String) -> Result<Json, Json.DecodeError>

type function on Json

Parses JSON text into a Json tree. Returns Err with a Json.DecodeError when the text is not one JSON value: a syntax error, or content after the first value.

A number with no fractional part and no exponent is an Int, exactly and at any size. Any other number is a Float.

assert Json.decode("{\"ok\":true,\"n\":42}")
    == Result.Ok(Json.Obj{"ok" => Json.Bool(True), "n" => Json.Int(42)})

assert Json.decode("123456789012345678901234567890")
    == Result.Ok(Json.Int(123_456_789_012_345_678_901_234_567_890))

assert Result.is_err(Json.decode("{"))
fn encode(jv: Json) -> String

type function on Json

Writes a Json tree as compact JSON text, with no whitespace between tokens.

A whole Float is written without a fraction: Float(36.0) is 36, which decode reads back as an Int.

assert Json.encode(Json.Int(Int.pow(2, 70))) == "1180591620717411303424"

assert Json.encode(Json.Obj{"ok" => Json.Bool(True), "n" => Json.Int(42)})
    == "{\"ok\":true,\"n\":42}"
fn to_dynamic(jv: Json) -> Dynamic

type function on Json

Converts a Json tree to a Dynamic of the same shape: strings, numbers, booleans, arrays, objects and null.

dyn = Json.to_dynamic(Json.String("hello"))
assert Dynamic.as_string(dyn) == Result.Ok("hello")
fn decode_as<T>(text: String) -> Result<T, Json.Error> where T: FromJson

type function on Json

Reads JSON text as a T in one step: Json.decode, then T.from_json. An Err is a Json.Error, Decode when the text is not JSON and Shape when its JSON is not a T. Give T with a binding’s annotation or as Json.decode_as<T>(text).

assert Json.decode_as<List<Int>>("[1, 2, 3]") == Ok([1, 2, 3])

names: Result<Map<String, Int>, Json.Error> = Json.decode_as(`{"a": 1}`)
assert names == Ok({"a" => 1})

shape = Json.decode_as<List<Int>>("[1, true]") |> Result.map_err(&Display.to_string(&1))
assert shape == Err("[1]: expected Int, got bool")

syntax = Json.decode_as<List<Int>>("[1,") |> Result.map_err(&Display.to_string(&1))

assert syntax
    == Err("json decode error at line 1, col 4: unexpected end of input: incomplete JSON value")
fn encode_as(value: ToJson) -> String

type function on Json

Writes a value as compact JSON text in one step: ToJson.to_json, then Json.encode. It is the other direction of Json.decode_as, and Json.decode_as reads its text back as the same value.

assert Json.encode_as([1, 2, 3]) == "[1,2,3]"
assert Json.encode_as({"a" => Some(1), "b" => None}) == `{"a":1,"b":null}`

text = Json.encode_as({"a" => [1, 2]})
assert Json.decode_as<Map<String, List<Int>>>(text) == Ok({"a" => [1, 2]})

assert Json.encode_as({error: "no todo 99"}) == `{"error":"no todo 99"}`
fn kind(jv: Json) -> String

type function on Json

The JSON value’s kind as a word: string, int, float, bool, array, object or null. A Json.ShapeError names it as what it got, beside the Nomi type it expected: expected String, got null.

impl Display for Json

fn to_string(jv: Json) -> String

impl Display.to_string

impl Debug for Json

fn inspect(jv: Json) -> String

impl Debug.inspect

impl ToJson for Json

fn to_json(value: Json) -> Json

impl ToJson.to_json

impl FromJson for Json

fn from_json(json: Json) -> Result<Json, Json.ShapeError>

impl FromJson.from_json

impl Equatable for Json

fn equal(a: Json, b: Json) -> Bool

impl Equatable.equal

subtype JsonObject Json when fn json ->
    case json
        .Obj(_) -> True
        _       -> False
    end
end

A Json value that is an object, Json.Obj: what a struct’s derived ToJson writes, and what jwt.sign_as signs. JsonObject.try_from(json) checks a value, so ToJson.to_json(x) of any ToJson becomes one, and JsonObject.fields reads its keys and values back.

subtype: JsonObject is a subtype of Json. A literal where a JsonObject is expected is checked when the program is compiled; JsonObject.try_from(...) checks a value when it runs.

import std::json.JsonObject

object = JsonObject.try_from(ToJson.to_json({id: 7}))!
assert JsonObject.fields(object) == {"id" => Json.Int(7)}
assert JsonObject.try_from(Json.Int(7)) == None
fn fields(object: JsonObject) -> Map<String, Json>

type function on JsonObject

The object’s keys and values.

fn try_from(value: Json) -> Maybe<JsonObject>

type function on JsonObject

Some of the value when it satisfies JsonObject’s rules, None when it does not.

struct Json.DecodeError
    message: String
    line: Int
    col: Int
    offset: Int
end

Why Json.decode failed, and where. line and col count from 1, for a reader. offset is the same place as a byte position counted from 0, and it is the position of the offending character, not the one after it.

decode produces these messages and no others, so code may match on them:

  • unexpected character 'x': a character that cannot appear there.
  • unexpected byte 0xff: a byte that begins no valid UTF-8 character.
  • unexpected end of input: incomplete JSON value: the input stopped inside a value.
  • unexpected end of input: expected a JSON value: the input was empty or blank.
  • trailing content after JSON value: a second value follows the first.
  • number out of range: <lexeme>: a well-formed number that cannot be held.
  • malformed JSON: a failure with no position to report.

A Json.DecodeError a program builds itself may carry any message.

impl Display for Json.DecodeError

fn to_string(e: Json.DecodeError) -> String

impl Display.to_string

impl Debug for Json.DecodeError

fn inspect(value: Json.DecodeError) -> String

impl Debug.inspect

enum Json.Error
    Decode Json.DecodeError
    Shape Json.ShapeError
end

Why Json.decode_as could not read its text as a T: the text is not JSON (Decode, with Json.decode’s error), or its JSON does not have T’s shape (Shape, with T.from_json’s error). Display writes the error it holds.

impl Display for Json.Error

fn to_string(e: Json.Error) -> String

impl Display.to_string

impl Debug for Json.Error

fn inspect(value: Json.Error) -> String

impl Debug.inspect

enum Json.Case
    Snake
    Camel
    Pascal
    Kebab
    ScreamingSnake
end

How a derived impl writes a struct’s field names as JSON object keys.

impl Debug for Json.Case

fn inspect(value: Json.Case) -> String

impl Debug.inspect

impl Display for Json.Case

fn to_string(value: Json.Case) -> String

impl Display.to_string

impl Equatable for Json.Case

fn equal(a: Json.Case, b: Json.Case) -> Bool

impl Equatable.equal

struct ToJson.Options
    rename_all: Json.Case = Json.Case.Snake
end

The options derive ToJson for T with ... accepts.

impl Debug for ToJson.Options

fn inspect(value: ToJson.Options) -> String

impl Debug.inspect

impl Equatable for ToJson.Options

fn equal(a: ToJson.Options, b: ToJson.Options) -> Bool

impl Equatable.equal

struct FromJson.Options
    rename_all: Json.Case = Json.Case.Snake
end

The options derive FromJson for T with ... accepts.

impl Debug for FromJson.Options

fn inspect(value: FromJson.Options) -> String

impl Debug.inspect

impl Equatable for FromJson.Options

fn equal(a: FromJson.Options, b: FromJson.Options) -> Bool

impl Equatable.equal

struct Json.ShapeError
    path: List<String>
    expected: String
    got: String
end

Why a Json tree could not be read as a typed Nomi value. Text that is not JSON is a Json.DecodeError instead. path is where in the tree the mismatch is, expected names the Nomi type the value was read as (String, List, Todo), and got is the JSON value’s kind (Json.kind), or missing for an absent key: title: expected String, got null.

impl Display for Json.ShapeError

fn to_string(e: Json.ShapeError) -> String

impl Display.to_string

impl Debug for Json.ShapeError

fn inspect(value: Json.ShapeError) -> String

impl Debug.inspect

fn shape_error_root(expected: String, got: Json) -> Json.ShapeError
fn shape_error_prepend(e: Json.ShapeError, segment: String) -> Json.ShapeError
fn decode_field<T>(fields: Map<String, Json>, key: String, expected: String) -> Result<T, Json.ShapeError> where T: FromJson
fn decode_defaulted_field<T>(fields: Map<String, Json>, key: String) -> Result<Maybe<T>, Json.ShapeError> where T: FromJson
interface ToJson
    fn to_json(value: self) -> Json
    fn to_json_field(value: self) -> Maybe<Json>
end

A type whose values are written as JSON: derive ToJson for T, or an impl. An anonymous struct is ToJson when each of its fields is: it is written as an object keyed by its field names as written, as derive ToJson writes a struct with the same fields. Each field writes its key with what its type’s to_json_field answers, and leaves the key out when that is None: a None field is null, and an Absent field (std::presence) is left out.

assert Json.encode_as({id: 7, tags: ["a"], due: None}) == `{"due":null,"id":7,"tags":["a"]}`
assert ToJson.to_json_field(3) == Some(Json.Int(3))
fn to_json(value: self) -> Json

interface ToJson

fn to_json_field(value: self) -> Maybe<Json>

interface ToJson

The JSON a struct field holding value writes under its key, or None to leave the key out. It is Some(to_json(value)) unless an impl writes its own, as Presence<T>’s does for Absent.

interface FromJson
    fn from_json(json: Json) -> Result<self, Json.ShapeError>
    fn from_missing() -> Maybe<self>
end

A type whose values are read from JSON: derive FromJson for T, or an impl. An anonymous struct is FromJson when each of its fields is, and reads an object as derive FromJson reads a struct with the same fields: each field from the key of its name, and keys it has no field for ignored. A missing key reads as its field’s type’s from_missing: None for a Maybe field, Absent for a Presence field (std::presence). When from_missing answers None, as it does for most types, the missing key is the error <key>: expected <type>, got missing.

todo = Json.decode_as<{title: String, order: Maybe<Int>}>(`{"title": "milk", "id": 3}`)
assert todo == Ok({title: "milk", order: None})

missing = Json.decode_as<{title: String}>("{}") |> Result.map_err(&Display.to_string(&1))
assert missing == Err("title: expected String, got missing")

assert Int.from_missing() == None
assert FromJson.from_missing<Maybe<Int>>() == Some(None)
fn from_json(json: Json) -> Result<self, Json.ShapeError>

interface FromJson

fn from_missing() -> Maybe<self>

interface FromJson

What a struct field of this type reads when its key is missing: Some(value), or None when a missing key is an error. It is None unless an impl writes its own, as Maybe<T>’s (Some(None)) and Presence<T>’s (Some(Absent)) do.

fn object_of_fields(fields: Map<String, Maybe<Json>>) -> Json

The object a struct’s fields write: each key with its field’s ToJson.to_json_field, and a key whose answer is None left out. derive ToJson writes a struct, and a struct variant’s payload, with it.