Module encoding/json
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
JSON parsing error type.
Variants
| Variant | Fields | Description |
|---|---|---|
UnexpectedChar | ch: 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. | |
Other | msg: 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) -> StringRender self under spec. An unrecognised spec degrades to the plain
to_string() rendering rather than failing.
Parameters
| Name | Type | Notes |
|---|---|---|
self | Self | |
spec | str |
Returns: String
Methods
to_string : (JsonError) fn(self : JsonError) -> Stringsource : (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
| Name | Type | Notes |
|---|---|---|
self | JsonError |
Dynamically-typed JSON value tree.
Variants
| Variant | Fields | Description |
|---|---|---|
Null | JSON null. | |
Bool | value: bool | JSON boolean. |
Number | value: f64 | JSON number (IEEE 754 double). |
Str | value: String | JSON string. |
Array | items: ArrayList(<enum:enum_decl_479664_file____home_runner_work_Yo_Yo_std_encoding_json_yo__self_shell>) | JSON array of values. |
Object | keys: 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) -> StringRender self under spec. An unrecognised spec degrades to the plain
to_string() rendering rather than failing.
Parameters
| Name | Type | Notes |
|---|---|---|
self | Self | |
spec | str |
Returns: String
impl(JsonValue, ...)
get : (JsonValue) fn(self : JsonValue, key : String) -> Option(JsonValue)at : (JsonValue) fn(self : JsonValue, index : usize) -> Option(JsonValue)as_bool : (JsonValue) fn(self : JsonValue) -> Option(bool)as_number : (JsonValue) fn(self : JsonValue) -> Option(f64)as_string : (JsonValue) fn(self : JsonValue) -> 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>))impl(JsonValue, ...)
is_null : (JsonValue) fn(self : JsonValue) -> boolis_bool : (JsonValue) fn(self : JsonValue) -> boolis_number : (JsonValue) fn(self : JsonValue) -> boolis_string : (JsonValue) fn(self : JsonValue) -> boolis_array : (JsonValue) fn(self : JsonValue) -> boolis_object : (JsonValue) fn(self : JsonValue) -> boolas_f64 : (JsonValue) fn(self : JsonValue) -> 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 i64 — serde_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
| Name | Type | Notes |
|---|---|---|
self | JsonValue |
Returns: Option(i64)
as_u64 : (JsonValue) fn(self : JsonValue) -> Option(u64)object : (JsonValue) fn() -> JsonValueAn empty JSON object — serde_json::Value::Object(Map::new()).
Returns: JsonValue
array : (JsonValue) fn() -> JsonValueAn 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
| Name | Type | Notes | Description |
|---|---|---|---|
self | JsonValue | ||
key | String | 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. | |
value | JsonValue | The member's value. |
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
| Name | Type | Notes | Description |
|---|---|---|---|
self | JsonValue | ||
key | String | 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. |
push : (JsonValue) fn(self : JsonValue, value : JsonValue) -> unitpointer : (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
| Name | Type | Notes |
|---|---|---|
self | JsonValue | |
path | String |
impl(JsonValue, Index(String)(...))
Output : JsonValueimpl(JsonValue, Index(usize)(...))
Output : JsonValueimpl(JsonValue, Default(...))
default : (JsonValue) fn() -> JsonValueThe default value of the type.
Returns: JsonValue
impl(JsonValue, ToString(...))
to_string : (JsonValue) fn(self : JsonValue) -> Stringimpl(JsonValue, Clone(...))
impl(JsonValue, Eq(JsonValue)(...))
impl(JsonValue, ToJson(...))
impl(JsonValue, FromJson(...))
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
| Name | Type | Description |
|---|---|---|
key | String | 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. |
value | JsonValue | The member's value. |
Traits / Modules
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) -> JsonValueImplementors
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)Implementors
Functions
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
| Name | Type | Notes | Description |
|---|---|---|---|
value | JsonValue | The member's value. | |
indent | usize |
Returns: String
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
| Name | Type | Notes |
|---|---|---|
s | String |
Serialise any ToJson value to JSON text.
Type Parameters
| Name | Type | Notes |
|---|---|---|
T | Type | comptime |
Parameters
| Name | Type | Notes |
|---|---|---|
v | T |
Returns: String
DEPRECATED, removed in v0.2.32: call json.encode.
Type Parameters
| Name | Type | Notes |
|---|---|---|
T | Type | comptime |
Parameters
| Name | Type | Notes |
|---|---|---|
v | T |
Returns: String