json
RFC 8259 JSON text, read into and written from the shared data model Value. Not auto-imported.
Json::parse(text) reads a Str into a Result<Value, JsonError>; Json::to_text(&value) writes an owned String in compact form and Json::to_pretty_text(&value) indents with two spaces. Json::write_text and Json::write_pretty_text append to a String the caller owns instead, so several values can be written into one buffer.
The parser is strict by RFC 8259: no trailing commas, no unquoted keys, no comments. Json::parse_with(text, &options) reads under JsonParseOptions, whose with_comments() takes // and /* */ comments wherever whitespace may stand, and a refusal's position counts them; the writers never write a comment. UTF-8 input is decoded into UTF-8 output, and \uXXXX escapes are decoded into the scalar values they name, surrogate pairs recombined. Objects and arrays may nest at most 256 deep, counted together; deeper input fails with DepthExceeded.
Integers in i64::MIN..=u64::MAX round-trip exactly as Number::Int / Number::UInt; a value containing a . or an exponent becomes Number::Float. Lossy float conversion happens only when the caller asks for as_f64().
A type is read from and written as JSON text in one step through FromJson and ToJson, which every type with FromValue (or ToValue) has. A type gets both from with [FromJson, ToJson], which derives FromValue and ToValue:
import std::encoding::json::{ FromJson, ToJson };
type struct Server with [FromJson, ToJson] {
public host: String;
public port: u16;
}
function main() -> int {
match (Server::from_json("{\"host\": \"example.com\", \"port\": 8080}")) {
Result::Ok(server) => {
const text: String = server.to_json(); // {"host":"example.com","port":8080}
return 0;
}
Result::Err(e) => { return 1; } // at .port: expected a u16, found a string
}
}
Types
Json
type struct Json {}
Static functions
static parse(text: Str) -> Result<Value, JsonError>;
static parse(text: Str) -> Result<Value, JsonError>;Read a complete JSON document, or say where it stops being JSON: the JsonError points at the first byte that failed. Trailing whitespace is allowed; trailing non-whitespace is JsonErrorKind::TrailingData. Arrays and objects nest at most 256 deep, counted together (JsonErrorKind::DepthExceeded).
static parse_with(text: Str, options: &JsonParseOptions) -> Result<Value, JsonError>;
static parse_with(text: Str, options: &JsonParseOptions) -> Result<Value, JsonError>;Read a complete JSON document as parse does, under options: with JsonParseOptions::with_comments(), a // comment to the end of its line and a /* */ comment may stand wherever whitespace may. A refusal's line and column count the comments' text, so they point into the text as written.
static to_text(value: &Value) -> String;
static to_text(value: &Value) -> String;value as compact JSON text, no whitespace between tokens: {"name":"cryo","tags":[1,2]}.
static to_pretty_text(value: &Value) -> String;
static to_pretty_text(value: &Value) -> String;value as JSON text indented by two spaces, object members and array elements one per line; an empty object or array stays on one line.
static write_text(out: mut &String, value: &Value) -> void;
static write_text(out: mut &String, value: &Value) -> void;Append value's compact JSON text to out.
static write_pretty_text(out: mut &String, value: &Value) -> void;
static write_pretty_text(out: mut &String, value: &Value) -> void;Append value's indented JSON text to out, as to_pretty_text writes it.
JsonParseOptions
type struct JsonParseOptions {
comments: boolean;
}
strict() is what Json::parse reads under; with_comments() also takes // and /* */ comments.
Properties
| Property | Type | Notes |
|---|---|---|
comments | boolean | Whether comments may stand where whitespace may. |
Constructors
static strict() -> JsonParseOptions;
static strict() -> JsonParseOptions;RFC 8259 exactly, as Json::parse reads.
static with_comments() -> JsonParseOptions;
static with_comments() -> JsonParseOptions;RFC 8259 with // and /* */ comments wherever whitespace may stand. The writers never write a comment.
FromJson
type trait FromJson {
static from_json(text: Str) -> Result<This, FromTextError<JsonError>>;
}
from_json parses the text and reads its value as the type. A refusal is a FromTextError<JsonError>: Parse when the text is not JSON, Decode when its value is not the type.
Constructors
static from_json(text: Str) -> Result<This, FromTextError<JsonError>>;
static from_json(text: Str) -> Result<This, FromTextError<JsonError>>;text read as a value of this type, or FromTextError::Parse with the JsonError where it is not JSON, or FromTextError::Decode with where its value is not this type.
ToJson
type trait ToJson {
to_json(&this) -> String;
to_pretty_json(&this) -> String;
}
Methods
to_json(&this) -> String;
to_json(&this) -> String;This value as compact JSON text, {"name":"cryo","tags":[1,2]}.
to_pretty_json(&this) -> String;
to_pretty_json(&this) -> String;This value as JSON text indented by two spaces, as Json::to_pretty_text writes it.
module encoding::json::error;
module encoding::json::parser;
module encoding::json::serializer;
export std::encoding::json::error::{ JsonError, JsonErrorKind };
| File | What it holds | Import |
|---|---|---|
error | JsonError, JsonErrorKind | import std::encoding::json::error; |
The reader and writer behind Json are internal to the module.
import a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
namespace std::encoding::json;json: RFC 8259 JSON text, read into and written from the shared data model std::encoding::value::Value.
type trait FromJson {
static from_json(text: Str) -> Result<This, FromTextError<JsonError>>;
}A type read from JSON text: the text parsed as Json::parse parses it, then its value read as the type through FromValue. Every type with FromValue has it, a type of its own through with [FromJson], which derives FromValue.
type trait ToJson {
to_json(&this) -> String;
to_pretty_json(&this) -> String;
}A type written as JSON text: its Value, from ToValue, written as Json::to_text writes one. Every type with ToValue has it, a type of its own through with [ToJson], which derives ToValue.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type struct Name {
field: Type;
method(&this) -> Ret { ... }
}A value type with named fields and optional methods. Structs live on the stack and are passed by value. Fields are public by default and may carry = default values; methods take their receiver as &this, mut &this, or this.
type struct Server with [FromJson, ToJson]type struct Point with [Eq, Clone, Debug] { .. }Asks the compiler to generate implementations of the listed traits for the type, each working through its fields or variants in declaration order. The derivable traits are Eq, Ord, Hash, Clone, Debug, Default, ToValue and FromValue, and the text formats' FromJson, ToJson, FromYaml, ToYaml, FromToml and ToToml. The clause comes after the name and its parameters, before where.
public function name() { ... }
public:Visible to any module that imports this one - the default for top-level items and for struct fields, so it is mostly written to be explicit. public: opens a visibility block that groups the members after it. A module is always public, so public module is refused (E0117).
Server.host: Stringtype struct String<A = GlobalAllocator> {}Owned, growable UTF-8 text. It dereferences to Str, the read-only view most text functions take, so every Str method reads a String too (s.contains(...), s.split(...)); as_str hands the view out.
Server.port: u16function name<T>(param: Type) -> Ret { ... }Declares a function. Parameters are written name: Type and are never inferred; the return type follows -> and defaults to void. Declaration order does not matter: every signature is collected before any body is checked, so functions may call each other freely and recurse.
function main() -> intmatch (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, constants, and tuple and destructuring patterns, such as (0, 1..8) or Option::Some((count, _)), and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
type struct Server with [FromJson, ToJson]type enum Result<T, E> with [Eq, Clone, Debug] {
Ok(T);
Err(E);
}The outcome of an operation that can fail: Ok(value) on success, Err(error) on failure.
Result::Ok(T)serverpattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
const name: Type = value;An immutable binding: it cannot be reassigned after initialisation. The annotation may be omitted when an initialiser is present - the binding takes the initialiser's concrete type, inferred locally. Mutability is opt-in through mut.
const text: Stringserverreturn value;Leaves the current function with the given value. A function whose return type is not void must return one; a bare return; is for void. In an async function it completes the future with the value.
Result::Err(E)etype struct Json {}The JSON text format: reading a Value from JSON text and writing one as JSON text.
type struct JsonParseOptions {
comments: boolean;
}How Json::parse_with reads: strict(), as Json::parse does, or with_comments(), taking // and /* */ comments as whitespace.
JsonParseOptions.comments: booleanWhether comments may stand where whitespace may.
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
type trait FromJson {
static from_json(text: Str) -> Result<This, FromTextError<JsonError>>;
}A type read from JSON text: the text parsed as Json::parse parses it, then its value read as the type through FromValue. Every type with FromValue has it, a type of its own through with [FromJson], which derives FromValue.
static name(param: Type) -> Ret { ... }A method that belongs to the type rather than an instance, called as Type::name(..). For structs, static new(..) returning a struct literal is the idiomatic constructor.
static FromJson::from_json(text: Str) -> Result<This, FromTextError<JsonError>>text read as a value of this type, or FromTextError::Parse with the JsonError where it is not JSON, or FromTextError::Decode with where its value is not this type.
(parameter) text: Strtype struct Str {}A read-only view of UTF-8 text owned elsewhere: a string literal, a String, a file's bytes. Copying a Str copies the view, not the text, and it is valid only while what it views is. Str::new("text") views a literal; String.as_str() views a String.
ThisThe implementing type, inside a trait or implement body. other: &This in a trait method is a reference to whichever type implements it; This::Item names an associated type.
type enum FromTextError<E> {
Parse(E);
Decode(ValueDecodeError);
}Why text could not be read as a type: it is not the format's text (Parse, holding the format's own error - a JsonError, YamlError or TomlError), or the value it holds is not the type (Decode).
type struct JsonError {
kind: JsonErrorKind;
line: u64;
column: u64;
offset: u64;
msg: String;
}Why JSON text could not be parsed, and where: the failure's kind, its position in the source, and a message for a person to read.
std::encoding::json::errortype trait ToJson {
to_json(&this) -> String;
to_pretty_json(&this) -> String;
}A type written as JSON text: its Value, from ToValue, written as Json::to_text writes one. Every type with ToValue has it, a type of its own through with [ToJson], which derives ToValue.
ToJson::to_json(&this) -> StringThis value as compact JSON text, {"name":"cryo","tags":[1,2]}.
&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
ToJson::to_pretty_json(&this) -> StringThis value as JSON text indented by two spaces, as Json::to_pretty_text writes it.
module collections::array;
module { a::b; a::c; }
internal module a::detail;In a directory's _module.cryo aggregator, declares a submodule. A module is public; internal module keeps it and everything it declares to its own package. The line is structure only: reaching the child's names still takes an import or an export.
namespace std::encoding::json::parser;Recursive-descent JSON parser.
namespace std::encoding::json::serializer;JSON serializer.
export a::b::Name;
export a::b::{ X, Y as Z };Passes a name this module did not declare on to its importers, exactly as if they had imported the same path - how an aggregator presents a flat surface over its files. Every hop is explicit, and there is no glob form.
language referencetype enum JsonErrorKind with [Eq, Clone] {
UnexpectedEof;
UnexpectedChar;
InvalidNumber;
InvalidEscape;
InvalidUnicode;
DepthExceeded;
TrailingData;
KeyNotString;
OutOfMemory;
}Closed set of failure kinds the JSON parser produces. New kinds are rare; most failures fold into one of these.
std::encoding::json::errortype struct Json {}The JSON text format: reading a Value from JSON text and writing one as JSON text.
static Json::parse(text: Str) -> Result<Value, JsonError>Read a complete JSON document, or say where it stops being JSON: the JsonError points at the first byte that failed. Trailing whitespace is allowed; trailing non-whitespace is JsonErrorKind::TrailingData. Arrays and objects nest at most 256 deep, counted together (JsonErrorKind::DepthExceeded).
type enum Value {
Null;
Bool(boolean);
Number(Number);
String(String);
Array(Array<Value>);
Object(Object);
}One JSON value. Recursive through Array and Object.
static Json::to_text(value: &Value) -> Stringvalue as compact JSON text, no whitespace between tokens: {"name":"cryo","tags":[1,2]}.
function value<T>() -> TA uniform value of type T: any integer width over its whole range, boolean, f32/f64 in [0.0, 1.0), or a char that is any Unicode scalar value.
static Json::to_pretty_text(value: &Value) -> Stringvalue as JSON text indented by two spaces, object members and array elements one per line; an empty object or array stays on one line.
static Json::write_text(out: mut &String, value: &Value) -> voidAppend value's compact JSON text to out.
static Json::write_pretty_text(out: mut &String, value: &Value) -> voidAppend value's indented JSON text to out, as to_pretty_text writes it.
static Json::parse_with(text: Str, options: &JsonParseOptions) -> Result<Value, JsonError>Read a complete JSON document as parse does, under options: with JsonParseOptions::with_comments(), a // comment to the end of its line and a /* */ comment may stand wherever whitespace may. A refusal's line and column count the comments' text, so they point into the text as written.
type struct JsonParseOptions {
comments: boolean;
}How Json::parse_with reads: strict(), as Json::parse does, or with_comments(), taking // and /* */ comments as whitespace.
static JsonParseOptions::with_comments() -> JsonParseOptionsRFC 8259 with // and /* */ comments wherever whitespace may stand. The writers never write a comment.
JsonErrorKind::DepthExceededObject/array nesting exceeded Parser::MAX_DEPTH.
start..=endAn inclusive range - start through end - and sugar for RangeInclusive::new(start, end). Also a match pattern: 1..=5 => { ... }.
type enum Number with [Debug, Clone] {
Int(i64);
UInt(u64);
Float(f64);
}JSON's single number type, split by source representation so integers round-trip exactly. Int covers signed values that fit i64; UInt carries values in (i64::MAX, u64::MAX]; everything else (decimals, exponents, NaN-shaped inputs the parser accepts as floats) is Float.
Number::Int(i64)Number::UInt(u64)Number::Float(f64)type trait ToValue {
to_value(&this) -> Value;
}A value that can be written as a Value.
type trait FromValue {
static from_value(value: &Value) -> Result<This, ValueDecodeError>;
}A value that can be read from a Value.
(parameter) options: &JsonParseOptions(parameter) value: &Value(parameter) out: mut &Stringmut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
static JsonParseOptions::strict() -> JsonParseOptionsRFC 8259 exactly, as Json::parse reads.
JsonParseOptions.comments: booleanWhether comments may stand where whitespace may.
std::encoding::jsonstatic FromJson::from_json(text: Str) -> Result<This, FromTextError<JsonError>>text read as a value of this type, or FromTextError::Parse with the JsonError where it is not JSON, or FromTextError::Decode with where its value is not this type.
FromTextError::Parse(E)The text is not the format's: what its reader refused, and where.
std::encoding::value::convertFromTextError::Decode(ValueDecodeError)The text's value is not the type: where in it, and what was wanted there.
std::encoding::value::convertToJson::to_json(&this) -> StringThis value as compact JSON text, {"name":"cryo","tags":[1,2]}.
ToJson::to_pretty_json(&this) -> StringThis value as JSON text indented by two spaces, as Json::to_pretty_text writes it.