Module encoding/json

encoding/json
Stability: unstable — two open questions, one of them a rename that touches every call site. The names still stutter (D2): `json_parse` / `json_parse_bytes` / `json_parse_string` / `json_stringify` repeat the module they live in, and the decided direction is `json.parse` / `json.stringify` on the imported module value. That rename is listed as STILL OPEN in `plans/STD_API_STABILIZATION.md` §4 and is the main thing holding this module unstable. `json_parse_result` is a deprecated alias of `json_parse_string`, kept for one release and due for removal. The second is how strict the string scanner should be. `parse_string` accepts a raw control byte (U+0000-U+001F) where RFC 8259 §7 requires it escaped, and copies non-escape bytes through without UTF-8 validation, so invalid UTF-8 in the input reaches the resulting `String`. `serde_json` rejects both. Tightening either one turns input that parses today into an error, so it is a breaking change rather than a bug fix (`issues/stddoc-io-json-parse-string-accepts-raw-control-bytes.md`). The value tree itself is settled: `JsonValue`'s six variants, the `is_*` / `as_*` accessors, `pointer`, `insert`/`remove`/`object`, and the `ToJson`/`FromJson` traits all landed with the P1 encoding batch and are covered by tests. — stable modules only change additively; this one may still change.

JSON parsing and serialization (RFC 8259).

Provides a dynamically-typed JSON value tree.

Example

json :: import("std/encoding/json");
{ JsonValue } :: import("std/encoding/json");
{ Exception } :: import "std/error";

exn := Exception(throw : ((err) -> { unwind (); }));
v := json.parse(`{"x": 1}`);
println(json.stringify(v));

Which parse to call

Three entry points, differing only in what they take: json_parse(str) for a literal, json_parse_string(String) for runtime text, and json_parse_bytes(ArrayList(u8)) for a network body. All three funnel into one parser over BYTES and all three return Result(JsonValue, JsonError). Each has a *_exn twin that throws through an Exception instead — take those only when the caller is already inside an effect scope, since D13 makes the Result form the primary one.

Parsing rejects trailing content: [1,2][3,4] is an error, not [1,2].

Stability

unstable — two open questions, one of them a rename that touches every call site.

The names still stutter (D2): json_parse / json_parse_bytes / json_parse_string / json_stringify repeat the module they live in, and the decided direction is json.parse / json.stringify on the imported module value. That rename is listed as STILL OPEN in plans/STD_API_STABILIZATION.md §4 and is the main thing holding this module unstable. json_parse_result is a deprecated alias of json_parse_string, kept for one release and due for removal.

The second is how strict the string scanner should be. parse_string accepts a raw control byte (U+0000-U+001F) where RFC 8259 §7 requires it escaped, and copies non-escape bytes through without UTF-8 validation, so invalid UTF-8 in the input reaches the resulting String. serde_json rejects both. Tightening either one turns input that parses today into an error, so it is a breaking change rather than a bug fix (issues/stddoc-io-json-parse-string-accepts-raw-control-bytes.md).

The value tree itself is settled: JsonValue's six variants, the is_* / as_* accessors, pointer, insert/remove/object, and the ToJson/FromJson traits all landed with the P1 encoding batch and are covered by tests.

Types

JsonError enum
JsonError

JSON parsing error type.

Variants

VariantFieldsDescription
UnexpectedCharch: u8, pos: usize

Encountered an unexpected character at the given position.

UnexpectedEnd

Input ended unexpectedly.

InvalidNumber

Failed to parse a numeric literal.

InvalidEscape

Invalid escape sequence in a string.

InvalidUnicode

Invalid Unicode unwind in a string.

Othermsg: String

Other error with a descriptive message.

Trait Implementations

impl(generic(T : Type), where(T <: ToString), T : (ToString))
impl(generic(T : Type), where(T <: ToString), T : (ToString), Format)
format : fn(self : Self, spec : str) -> String

Render self under spec. An unrecognised spec degrades to the plain to_string() rendering rather than failing.

Parameters

NameTypeNotes
selfSelf
specstr

Returns: String

Methods
to_string : (JsonError) fn(self : JsonError) -> String

Parameters

NameTypeNotes
selfJsonError

Returns: String

source : (JsonError) fn(self : JsonError) -> Option(dyn( + ToString))

The error that caused this one, or .None at the root of the chain.

Rust's Error::source. Defaulted to .None, so an error with nothing underneath it implements the trait by saying only what it is; a wrapper overrides it to hand back what it wrapped. Walking the chain to the root cause is not expressible yet — the returned Dyn loses the Error trait on an erased receiver, so a caller can print one link but cannot follow it (#521, issues/self-trait-in-a-return-type-loses-the-trait-on-an-erased-receiver.md).

Parameters

NameTypeNotes
selfJsonError

Returns: Option(dyn( + ToString))

JsonValue enum
JsonValue

Dynamically-typed JSON value tree.

Variants

VariantFieldsDescription
Null

JSON null.

Boolvalue: bool

JSON boolean.

Numbervalue: f64

JSON number (IEEE 754 double).

Strvalue: String

JSON string.

Arrayitems: ArrayList(<enum:enum_decl_479664_file____home_runner_work_Yo_Yo_std_encoding_json_yo__self_shell>)

JSON array of values.

Objectkeys: ArrayList(String), values: ArrayList(<enum:enum_decl_479664_file____home_runner_work_Yo_Yo_std_encoding_json_yo__self_shell>)

JSON object with ordered key-value pairs.

Trait Implementations

impl(generic(T : Type), where(T <: ToString), T : (ToString))
impl(generic(T : Type), where(T <: ToString), T : (ToString), Format)
format : fn(self : Self, spec : str) -> String

Render self under spec. An unrecognised spec degrades to the plain to_string() rendering rather than failing.

Parameters

NameTypeNotes
selfSelf
specstr

Returns: String

impl(JsonValue, ...)
get : (JsonValue) fn(self : JsonValue, key : String) -> Option(JsonValue)

Get a field from an Object value by key. Returns .None if not an Object or key is missing.

Parameters

NameTypeNotesDescription
selfJsonValue
keyString

The member name, DECODED — escapes in the source are already resolved, so this is the key as JSON means it and not as it was written.

Returns: Option(JsonValue)

at : (JsonValue) fn(self : JsonValue, index : usize) -> Option(JsonValue)

Get an element from an Array value by index.

Parameters

NameTypeNotes
selfJsonValue
indexusize

Returns: Option(JsonValue)

as_bool : (JsonValue) fn(self : JsonValue) -> Option(bool)

Extract the boolean value, or .None if not a Bool.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(bool)

as_number : (JsonValue) fn(self : JsonValue) -> Option(f64)

Extract the numeric value, or .None if not a Number.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(f64)

as_string : (JsonValue) fn(self : JsonValue) -> Option(String)

Extract the string value, or .None if not a Str.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(String)

as_array : (JsonValue) fn(self : JsonValue) -> Option(ArrayList(<enum:enum_decl_479664_file____home_runner_work_Yo_Yo_std_encoding_json_yo__self_shell>))

Extract the array items, or .None if not an Array.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(ArrayList(<enum:enum_decl_479664_file____home_runner_work_Yo_Yo_std_encoding_json_yo__self_shell>))

as_object : (JsonValue) fn(self : JsonValue) -> Option(ArrayList(JsonKV))

Extract object entries as ArrayList(JsonKV), or .None if not an Object.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(ArrayList(JsonKV))

impl(JsonValue, ...)
is_null : (JsonValue) fn(self : JsonValue) -> bool

True for JSON null.

Parameters

NameTypeNotes
selfJsonValue

Returns: bool

is_bool : (JsonValue) fn(self : JsonValue) -> bool

True for a JSON boolean.

Parameters

NameTypeNotes
selfJsonValue

Returns: bool

is_number : (JsonValue) fn(self : JsonValue) -> bool

True for a JSON number.

Parameters

NameTypeNotes
selfJsonValue

Returns: bool

is_string : (JsonValue) fn(self : JsonValue) -> bool

True for a JSON string.

Parameters

NameTypeNotes
selfJsonValue

Returns: bool

is_array : (JsonValue) fn(self : JsonValue) -> bool

True for a JSON array.

Parameters

NameTypeNotes
selfJsonValue

Returns: bool

is_object : (JsonValue) fn(self : JsonValue) -> bool

True for a JSON object.

Parameters

NameTypeNotes
selfJsonValue

Returns: bool

as_f64 : (JsonValue) fn(self : JsonValue) -> Option(f64)

The numeric value as an f64 — Rust's name for what as_number already did. Both spellings are kept: as_f64 sits beside as_i64 / as_u64, and as_number is what the rest of this module calls.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(f64)

as_i64 : (JsonValue) fn(self : JsonValue) -> Option(i64)

The numeric value as an i64, or .None when it is not a number, not integral, or outside i64serde_json::Value::as_i64's contract.

JSON numbers are IEEE-754 doubles here (there is no separate integer arm), so "integral" is decided by a round trip: 2^63 is exactly representable as a double, which makes [-2^63, 2^63) an exact bound, and NaN / ±infinity fail both comparisons and land in .None.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(i64)

as_u64 : (JsonValue) fn(self : JsonValue) -> Option(u64)

The numeric value as a u64, or .None when it is not a number, not integral, negative, or outside u64serde_json::Value::as_u64.

Parameters

NameTypeNotes
selfJsonValue

Returns: Option(u64)

object : (JsonValue) fn() -> JsonValue

An empty JSON object — serde_json::Value::Object(Map::new()).

Returns: JsonValue

array : (JsonValue) fn() -> JsonValue

An empty JSON array.

Returns: JsonValue

insert : (JsonValue) fn(self : JsonValue, key : String, value : JsonValue) -> Option(JsonValue)

Set key to value, returning the value it REPLACED (.None when the key is new) — serde_json's Map::insert. Insertion order is preserved and a replacement keeps the key's original position.

Panics when self is not an object.

Parameters

NameTypeNotesDescription
selfJsonValue
keyString

The member name, DECODED — escapes in the source are already resolved, so this is the key as JSON means it and not as it was written.

valueJsonValue

The member's value.

Returns: Option(JsonValue)

remove : (JsonValue) fn(self : JsonValue, key : String) -> Option(JsonValue)

Remove key, returning its value (.None when absent) — serde_json's Map::remove. The remaining keys keep their order.

Panics when self is not an object.

Parameters

NameTypeNotesDescription
selfJsonValue
keyString

The member name, DECODED — escapes in the source are already resolved, so this is the key as JSON means it and not as it was written.

Returns: Option(JsonValue)

push : (JsonValue) fn(self : JsonValue, value : JsonValue) -> unit

Append value to an array.

Panics when self is not an array.

Parameters

NameTypeNotesDescription
selfJsonValue
valueJsonValue

The member's value.

Returns: unit

pointer : (JsonValue) fn(self : JsonValue, path : String) -> Option(JsonValue)

Resolve an RFC 6901 JSON Pointer — serde_json::Value::pointer.

"" is the whole document. Otherwise the pointer must start with / and each following token names an object key or an array index, with ~1 decoding to / and ~0 to ~. An array index must be 0 or a digit string with no leading zero, as the RFC requires — "01" is not a valid index and resolves to .None, not to element 1.

Parameters

NameTypeNotes
selfJsonValue
pathString

Returns: Option(JsonValue)

impl(JsonValue, Index(String)(...))
Output : JsonValue
index : (JsonValue) fn(self : JsonValue, idx : usize) -> *(JsonValue)

Parameters

NameTypeNotes
selfJsonValue
idxusize

Returns: *(JsonValue)

impl(JsonValue, Index(usize)(...))
Output : JsonValue
index : (JsonValue) fn(self : JsonValue, idx : usize) -> *(JsonValue)

Parameters

NameTypeNotes
selfJsonValue
idxusize

Returns: *(JsonValue)

impl(JsonValue, Default(...))
default : (JsonValue) fn() -> JsonValue

The default value of the type.

Returns: JsonValue

impl(JsonValue, ToString(...))
to_string : (JsonValue) fn(self : JsonValue) -> String

Render self as the text a USER should read — Rust's Display::fmt, not its Debug. Hand-written (or generated by derive(Error) from a per-variant format string) whenever the structural form would be wrong.

Parameters

NameTypeNotes
selfJsonValue

Returns: String

impl(JsonValue, Clone(...))
clone : (JsonValue) fn(self : JsonValue) -> JsonValue

Create an independent clone of self.

Parameters

NameTypeNotes
selfJsonValue

Returns: JsonValue

impl(JsonValue, Eq(JsonValue)(...))
impl(JsonValue, ToJson(...))
to_json : (JsonValue) fn(self : JsonValue) -> JsonValue

Parameters

NameTypeNotes
selfJsonValue

Returns: JsonValue

impl(JsonValue, FromJson(...))
from_json : (JsonValue) fn(v : JsonValue) -> Result(JsonValue, JsonError)

Parameters

NameTypeNotes
vJsonValue

Returns: Result(JsonValue, JsonError)

Methods
== : (JsonValue) fn(lhs : JsonValue, rhs : JsonValue) -> bool

Parameters

NameTypeNotes
lhsJsonValue
rhsJsonValue

Returns: bool

!= : (JsonValue) fn(lhs : JsonValue, rhs : JsonValue) -> bool

Parameters

NameTypeNotes
lhsJsonValue
rhsJsonValue

Returns: bool

JsonKV struct
JsonKV

Key-value pair for JSON object entries.

JsonValue.Object stores two parallel ArrayLists (keys and values) rather than a list of pairs, because that is what keeps insertion order without a per-entry allocation. as_object() zips them into these for iteration; it is the only producer, and nothing in the module consumes them — building an object goes through object() / insert instead.

Fields

NameTypeDescription
keyString

The member name, DECODED — escapes in the source are already resolved, so this is the key as JSON means it and not as it was written.

valueJsonValue

The member's value.

Traits / Modules

ToJson trait
ToJson

Serialise a value to a JsonValue tree. Implement (or later, derive) this to make a type encodable; the text form always goes through stringify, so formatting stays centralized.

Methods

to_json : fn(self : Self) -> JsonValue

Parameters

NameTypeNotes
selfSelf

Returns: JsonValue

Implementors

FromJson trait
FromJson

Deserialise a value from a JsonValue tree. Returns Result rather than throwing: decode failures are ordinary values a caller matches on, and JsonError can grow structured variants without breaking this signature. Call as T.from_json(v) or through decode.

Methods

from_json : fn(v : JsonValue) -> Result(Self, JsonError)

Parameters

NameTypeNotes
vJsonValue

Returns: Result(Self, JsonError)

Implementors

Functions

parse function
fn(s : str) -> Result(JsonValue, JsonError)

Parse a static str of JSON into a JsonValue tree.

Parameters

NameTypeNotes
sstr

Returns: Result(JsonValue, JsonError)

parse_bytes function
fn(bytes : ArrayList(u8)) -> Result(JsonValue, JsonError)

Parse JSON bytes into a JsonValue tree (D13 — a pure transform returns a Result). .Err on invalid input, INCLUDING any content after the single top-level value.

Parameters

NameTypeNotes
bytesArrayList(u8)

Returns: Result(JsonValue, JsonError)

parse_string function
fn(s : String) -> Result(JsonValue, JsonError)

Parse a runtime String of JSON into a JsonValue tree. (parse takes the STATIC str view; runtime input — an HTTP body, an LSP frame — arrives as String.)

Parameters

NameTypeNotes
sString

Returns: Result(JsonValue, JsonError)

parse_exn function
fn(s : str, exn : Exception) -> JsonValue

parse as an effect.

Parameters

NameTypeNotes
sstr
exnException

Returns: JsonValue

parse_bytes_exn function
fn(bytes : ArrayList(u8), exn : Exception) -> JsonValue

parse_bytes as an effect, for callers already inside an effect scope. Same for the two below.

Parameters

NameTypeNotes
bytesArrayList(u8)
exnException

Returns: JsonValue

parse_string_exn function
fn(s : String, exn : Exception) -> JsonValue

parse_string as an effect.

Parameters

NameTypeNotes
sString
exnException

Returns: JsonValue

stringify function
fn(value : JsonValue) -> String

Serialize a JsonValue to a compact JSON string.

Parameters

NameTypeNotesDescription
valueJsonValue

The member's value.

Returns: String

stringify_pretty function
fn(value : JsonValue, indent : usize) -> String

Serialize a JsonValue to a pretty-printed JSON string, indent spaces per nesting level. indent == 0 produces the compact form, as JSON.stringify(v, null, 0) does.

Parameters

NameTypeNotesDescription
valueJsonValue

The member's value.

indentusize

Returns: String

fn(s : String) -> Result(JsonValue, JsonError)

Parse a JSON String into a JsonValue, as a Result (no Exception plumbing — the decode-side counterpart of json.stringify). DEPRECATED (D13), removed in v0.2.32 with the module-prefix aliases below: json.parse_string returns the same Result. This name existed only because json.parse* used to throw.

Parameters

NameTypeNotes
sString

Returns: Result(JsonValue, JsonError)

encode function
fn(generic(T : Type), v : T, where(T <: ToJson)) -> String

Serialise any ToJson value to JSON text.

Type Parameters

NameTypeNotes
TTypecomptime

Parameters

NameTypeNotes
vT

Returns: String

decode function
fn(comptime(T) : Type, s : String, where(T <: FromJson)) -> Result(T, JsonError)

Parse JSON text and decode it into T: json.decode(Point, s)Result(Point, JsonError).

Parameters

NameTypeNotes
TTypecomptime
sString

Returns: Result(T, JsonError)

json_parse function
fn(s : str) -> Result(JsonValue, JsonError)

DEPRECATED, removed in v0.2.32: call json.parse.

Parameters

NameTypeNotes
sstr

Returns: Result(JsonValue, JsonError)

json_parse_bytes function
fn(bytes : ArrayList(u8)) -> Result(JsonValue, JsonError)

DEPRECATED, removed in v0.2.32: call json.parse_bytes.

Parameters

NameTypeNotes
bytesArrayList(u8)

Returns: Result(JsonValue, JsonError)

fn(s : String) -> Result(JsonValue, JsonError)

DEPRECATED, removed in v0.2.32: call json.parse_string.

Parameters

NameTypeNotes
sString

Returns: Result(JsonValue, JsonError)

json_parse_exn function
fn(s : str, exn : Exception) -> JsonValue

DEPRECATED, removed in v0.2.32: call json.parse_exn.

Parameters

NameTypeNotes
sstr
exnException

Returns: JsonValue

fn(bytes : ArrayList(u8), exn : Exception) -> JsonValue

DEPRECATED, removed in v0.2.32: call json.parse_bytes_exn.

Parameters

NameTypeNotes
bytesArrayList(u8)
exnException

Returns: JsonValue

fn(s : String, exn : Exception) -> JsonValue

DEPRECATED, removed in v0.2.32: call json.parse_string_exn.

Parameters

NameTypeNotes
sString
exnException

Returns: JsonValue

json_stringify function
fn(value : JsonValue) -> String

DEPRECATED, removed in v0.2.32: call json.stringify.

Parameters

NameTypeNotesDescription
valueJsonValue

The member's value.

Returns: String

fn(value : JsonValue, indent : usize) -> String

DEPRECATED, removed in v0.2.32: call json.stringify_pretty.

Parameters

NameTypeNotesDescription
valueJsonValue

The member's value.

indentusize

Returns: String

json_encode function
fn(generic(T : Type), v : T, where(T <: ToJson)) -> String

DEPRECATED, removed in v0.2.32: call json.encode.

Type Parameters

NameTypeNotes
TTypecomptime

Parameters

NameTypeNotes
vT

Returns: String

json_decode function
fn(comptime(T) : Type, s : String, where(T <: FromJson)) -> Result(T, JsonError)

DEPRECATED, removed in v0.2.32: call json.decode.

Parameters

NameTypeNotes
TTypecomptime
sString

Returns: Result(T, JsonError)