core:json
JSON serialization and deserialization (self-describing format).
Implements the core:serde Serializer and Deserializer traits for JSON.
Serde I/O is bytes-primary: prefer to_bytes / from_bytes when the data
is consumed as bytes. to_bytes_pretty and to_bytes_canonical cover the
indented and the deterministic (sorted-key) forms.
Where JSON readers disagree
RFC 8259 leaves number range and precision, lone surrogates and repeated keys to the implementation, and readers that settle them differently read one document as different values. This module settles each one as follows.
Numbers
- The target type decides between integer and float, not the token's spelling.
- Every number type reads a number, or a string holding exactly one number
token, by one rule.
"1.5"reads as a float,"NaN"and" 1"as none. - Every integer type reads exactly at any width.
1.0,1e2and10e-1read when the value is integral and in range.1.5is anUnexpectedTypeerror and a value out of the type's range anOverflow.-0reads as0, unsigned or not. - A float reads as the decimal rounded once to the nearest value of its
type, however many digits it spells.
0.000…0001e400with 400 zeros reads as exactly0.1. - A number that rounds to infinity in its type is an
Overflow(1e400asf64,3.5e38asf32). One too small for the type reads as a zero of its sign.-0reads as-0.0. - A
Valueholds every number asFloat, as JavaScript does, so an integer past 2^53 loses precision there. Read into an integer type to keep it. - The writer refuses
NaNand infinity. The serialization chapter of the specification says which integers it writes as strings.
Strings
- A
\uXXXXhigh surrogate followed by a low one decodes to one character. A lone surrogate is aMalformedInputerror. - Raw bytes must be valid UTF-8.
\u0000is allowed.
Objects
- A repeated key is a
DuplicateFielderror, into a struct, a map and aValuealike. Keys compare after unescaping, so"a\/b"repeats"a/b". - A map and a
Valuekeep keys in document order.to_bytes_canonicalwrites them sorted, as RFC 8785 (JCS) does. - A struct ignores a key it has no field for. The value under it is held
to the grammar alone, so
1e400there is no error. - A map key is a string, and a numeric key type holds what it spells to the
number rules above, as serde_json does:
"1e2"is thei32key100,"1e400"anOverflowas anf64key, and"NaN","inf"and"+5"no number. Writing a NaN or infinite key is an error, as writing such a value is.
Documents
- A byte-order mark or anything but whitespace after the value is an error.
- Nesting deeper than
max_depthis an error.
Synopsis
struct Point {
x: i32,
y: i32,
}
impl Serialize for Point;
impl Deserialize for Point;
assert to_string(&Point { x: 1, y: 2 }) matches { Ok(s) && s == "{\"x\":1,\"y\":2}" };
assert from_string::<Point>("{\"x\":1,\"y\":2}") matches { Ok(p) && p.x == 1 && p.y == 2 };
Functions
pub fn write_escaped_string<S: AsStrSlice>(buf: &mut String, s: S)
Writes a JSON-escaped string (with surrounding quotes) into buf. Only ",
\, and controls (< 0x20) are escaped — all ASCII, so a run of multi-byte
UTF-8 copies through unchanged.
pub fn to_string<T: Serialize>(value: &T, trailing_char: Option<char> = null) -> Result<String, SerializeError>
Serializes a value to a JSON string. Convenience over to_bytes for text
contexts; serde I/O is bytes-primary, so prefer to_bytes when the output
is read as bytes (e.g. an HTTP response body).
trailing_char, when Some, is appended after the value — pass
Option::Some('\n') to emit JSON Lines (one record per line).
pub fn to_bytes<T: Serialize>(value: &T, trailing_char: Option<char> = null) -> Result<ByteSlice, SerializeError>
Serializes a value directly to UTF-8 JSON bytes.
Returns a read-only ByteSlice over the serializer's UTF-8 buffer. Prefer this
over to_string(value).bytes().collect() whenever the output is read as bytes
(e.g. an HTTP response body).
trailing_char, when Some, is appended after the value — pass
Option::Some('\n') to emit JSON Lines.
pub fn to_string_pretty<T: Serialize>(value: &T, trailing_char: Option<char> = null) -> Result<String, SerializeError>
Serializes a value to a pretty JSON string. Convenience over
to_bytes_pretty; serde I/O is bytes-primary.
trailing_char, when Some, is appended after the value.
pub fn from_string<T: Deserialize, S: AsStrSlice>(input: S, max_depth: i32 = DEFAULT_MAX_DEPTH) -> Result<T, DeserializeError>
Deserializes a value from a JSON string. Convenience wrapper over
from_bytes, which every text source reaches through its own UTF-8 bytes;
serde I/O is bytes-primary.
pub fn from_bytes<T: Deserialize, S: AsByteSlice>(input: S, max_depth: i32 = DEFAULT_MAX_DEPTH) -> Result<T, DeserializeError>
Deserializes a value from UTF-8 JSON bytes — the primary entry point.
Accepts any AsByteSlice source, scanned in place; every string token is
validated as UTF-8 (RFC 8259 §8.1). max_depth bounds nesting.
pub fn to_bytes_canonical<T: Serialize>(value: &T, trailing_char: Option<char> = null) -> Result<ByteSlice, SerializeError>
Serializes a value to UTF-8 JSON bytes in the JSON Canonicalization Scheme
(RFC 8785): keys sorted by their UTF-16 code units, numbers in ECMAScript's
form, strings escaped as JSON.stringify escapes them. Equal values produce
byte-identical output regardless of map insertion order, and any JCS
implementation canonicalizing that output reproduces it byte for byte. An
f32 keeps its own shortest digits and an integer past 2^53 its string form,
so a JCS implementation starting from the same values as doubles writes
those differently. Use this for signing or content addressing; use
to_bytes for the faster insertion-order form.
Returns a read-only ByteSlice over the serializer's UTF-8 buffer.
trailing_char, when Some, is appended after the value; leave it null
(the default) to keep the byte-exact canonical form for signing.
pub fn to_bytes_pretty<T: Serialize>(value: &T, trailing_char: Option<char> = null) -> Result<ByteSlice, SerializeError>
Serializes a value to pretty-printed UTF-8 JSON bytes.
Returns a read-only ByteSlice over the serializer's UTF-8 buffer.
trailing_char, when Some, is appended after the value.
Structs
pub struct JsonSeqSerializer
Fields are private.
impl SerializeSeq for JsonSeqSerializer
fn element<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct JsonMapSerializer
Fields are private.
impl SerializeMap for JsonMapSerializer
fn key<T: Serialize>(&mut self, key: &T) -> Result<(), SerializeError>
fn value<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct JsonStructSerializer
Fields are private.
impl SerializeStruct for JsonStructSerializer
fn field<T: Serialize, S: AsStrSlice>(&mut self, name: S, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct JsonVariantSerializer
Fields are private.
impl SerializeVariant for JsonVariantSerializer
fn payload<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct JsonSerializer
Fields are private.
impl Serializer for JsonSerializer
fn serialize_i32(&mut self, v: i32) -> Result<(), SerializeError>
fn serialize_i64(&mut self, v: i64) -> Result<(), SerializeError>
fn serialize_u32(&mut self, v: u32) -> Result<(), SerializeError>
fn serialize_u64(&mut self, v: u64) -> Result<(), SerializeError>
fn serialize_i128(&mut self, v: i128) -> Result<(), SerializeError>
fn serialize_u128(&mut self, v: u128) -> Result<(), SerializeError>
fn serialize_f32(&mut self, v: f32) -> Result<(), SerializeError>
fn serialize_f64(&mut self, v: f64) -> Result<(), SerializeError>
fn serialize_bool(&mut self, v: bool) -> Result<(), SerializeError>
fn serialize_char(&mut self, v: char) -> Result<(), SerializeError>
fn serialize_string<S: AsStrSlice>(&mut self, v: S) -> Result<(), SerializeError>
fn serialize_bytes(&mut self, v: ByteSlice) -> Result<(), SerializeError>
fn serialize_null(&mut self) -> Result<(), SerializeError>
fn begin_seq(&mut self, len: i32) -> Result<JsonSeqSerializer, SerializeError>
fn begin_map(&mut self, len: i32) -> Result<JsonMapSerializer, SerializeError>
fn begin_struct<S: AsStrSlice>(&mut self, name: S, fields: i32) -> Result<JsonStructSerializer, SerializeError>
fn serialize_unit_variant<S: AsStrSlice, S1: AsStrSlice>(&mut self, type_name: S, variant_name: S1, disc: i32) -> Result<(), SerializeError>
fn begin_variant<S: AsStrSlice, S1: AsStrSlice>(&mut self, type_name: S, variant_name: S1, disc: i32) -> Result<JsonVariantSerializer, SerializeError>
pub struct PrettyJsonSeqSerializer
Fields are private.
impl SerializeSeq for PrettyJsonSeqSerializer
fn element<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct PrettyJsonMapSerializer
Fields are private.
impl SerializeMap for PrettyJsonMapSerializer
fn key<T: Serialize>(&mut self, key: &T) -> Result<(), SerializeError>
fn value<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct PrettyJsonStructSerializer
Fields are private.
impl SerializeStruct for PrettyJsonStructSerializer
fn field<T: Serialize, S: AsStrSlice>(&mut self, name: S, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct PrettyJsonVariantSerializer
Fields are private.
impl SerializeVariant for PrettyJsonVariantSerializer
fn payload<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct PrettyJsonSerializer
buf: &mut String
indent: &String
depth: i32
impl Serializer for PrettyJsonSerializer
fn serialize_i32(&mut self, v: i32) -> Result<(), SerializeError>
fn serialize_i64(&mut self, v: i64) -> Result<(), SerializeError>
fn serialize_u32(&mut self, v: u32) -> Result<(), SerializeError>
fn serialize_u64(&mut self, v: u64) -> Result<(), SerializeError>
fn serialize_i128(&mut self, v: i128) -> Result<(), SerializeError>
fn serialize_u128(&mut self, v: u128) -> Result<(), SerializeError>
fn serialize_f32(&mut self, v: f32) -> Result<(), SerializeError>
fn serialize_f64(&mut self, v: f64) -> Result<(), SerializeError>
fn serialize_bool(&mut self, v: bool) -> Result<(), SerializeError>
fn serialize_char(&mut self, v: char) -> Result<(), SerializeError>
fn serialize_string<S: AsStrSlice>(&mut self, v: S) -> Result<(), SerializeError>
fn serialize_bytes(&mut self, v: ByteSlice) -> Result<(), SerializeError>
fn serialize_null(&mut self) -> Result<(), SerializeError>
fn begin_seq(&mut self, len: i32) -> Result<PrettyJsonSeqSerializer, SerializeError>
fn begin_map(&mut self, len: i32) -> Result<PrettyJsonMapSerializer, SerializeError>
fn begin_struct<S: AsStrSlice>(&mut self, name: S, fields: i32) -> Result<PrettyJsonStructSerializer, SerializeError>
fn serialize_unit_variant<S: AsStrSlice, S1: AsStrSlice>(&mut self, type_name: S, variant_name: S1, disc: i32) -> Result<(), SerializeError>
fn begin_variant<S: AsStrSlice, S1: AsStrSlice>(&mut self, type_name: S, variant_name: S1, disc: i32) -> Result<PrettyJsonVariantSerializer, SerializeError>
pub struct JsonDeserializer
input: ByteSlice
pos: i32
depth: i32
Nesting level of the value being read. Each access re-asserts its own level before descending, so it never needs unwinding.
max_depth: i32
pub fn peek(&self) -> i32
pub fn advance(&mut self)
pub fn peek_after_whitespace(&mut self) -> i32
Advances pos past any run of JSON whitespace and returns the byte it
stops on, or -1 at end of input. Use that byte: reading it back out of
the input costs another bounds check and load.
pub fn expect_char(&mut self, c: i32) -> Result<(), DeserializeError>
pub fn read_json_string(&mut self) -> Result<String, DeserializeError>
pub fn skip_number(&mut self) -> Result<(), DeserializeError>
Advances past the JSON number at pos without allocating a String,
held to the grammar every number read is.
pub fn parse_i32_direct(&mut self) -> Result<i32, DeserializeError>
Parses an i32 directly from self.input, without an intermediate
String allocation.
pub fn parse_i64_direct(&mut self) -> Result<i64, DeserializeError>
Parses an i64 directly from self.input, without an intermediate
String allocation.
pub fn parse_u64_direct(&mut self) -> Result<u64, DeserializeError>
Parses a u64 directly from self.input, without an intermediate String
allocation for a plain integer.
pub fn parse_f64_direct(&mut self) -> Result<f64, DeserializeError>
Parses an f64 directly from self.input using fpfmt, without an
intermediate String allocation.
pub fn parse_f32_direct(&mut self) -> Result<f32, DeserializeError>
parse_f64_direct, rounded once into f32 rather than through f64.
pub fn skip_string(&mut self) -> Result<(), DeserializeError>
Skips a string token without allocating. Shares scan_string_run and
read_escape with the reading path, so a skipped string is held to the
same rules as a materialized one.
pub fn skip_value(&mut self, depth: i32) -> Result<(), DeserializeError>
Skips the next JSON value without allocating.
impl Deserializer for JsonDeserializer
fn deserialize_i32(&mut self) -> Result<i32, DeserializeError>
fn deserialize_i64(&mut self) -> Result<i64, DeserializeError>
fn deserialize_u32(&mut self) -> Result<u32, DeserializeError>
fn deserialize_u64(&mut self) -> Result<u64, DeserializeError>
fn deserialize_i128(&mut self) -> Result<i128, DeserializeError>
fn deserialize_u128(&mut self) -> Result<u128, DeserializeError>
fn deserialize_f32(&mut self) -> Result<f32, DeserializeError>
fn deserialize_f64(&mut self) -> Result<f64, DeserializeError>
fn deserialize_f16(&mut self) -> Result<f16, DeserializeError>
fn deserialize_bf16(&mut self) -> Result<bf16, DeserializeError>
fn deserialize_bool(&mut self) -> Result<bool, DeserializeError>
fn deserialize_char(&mut self) -> Result<char, DeserializeError>
fn deserialize_string(&mut self) -> Result<String, DeserializeError>
fn deserialize_bytes(&mut self) -> Result<ByteList, DeserializeError>
fn is_null(&mut self) -> Result<bool, DeserializeError>
fn begin_seq(&mut self) -> Result<JsonSeqAccess, DeserializeError>
fn begin_map(&mut self) -> Result<JsonMapAccess, DeserializeError>
fn begin_struct<S: AsStrSlice>(&mut self, name: S, num_fields: i32) -> Result<JsonStructAccess, DeserializeError>
fn begin_variant<S: AsStrSlice>(&mut self, type_name: S, num_cases: i32) -> Result<JsonVariantAccess, DeserializeError>
fn deserialize_any<V: Visitor>(&mut self, visitor: &mut V) -> Result<V::Value, DeserializeError>
pub struct JsonSeqAccess
Fields are private.
impl DeserializeSeq for JsonSeqAccess
fn next_element<T: Deserialize>(&mut self) -> Result<Option<T>, DeserializeError>
fn end(&mut self) -> Result<(), DeserializeError>
pub struct JsonMapAccess
Fields are private.
impl DeserializeMap for JsonMapAccess
fn next_key<K: Deserialize>(&mut self) -> Result<Option<K>, DeserializeError>
fn next_value<V: Deserialize>(&mut self) -> Result<V, DeserializeError>
fn end(&mut self) -> Result<(), DeserializeError>
pub struct JsonStructAccess
Fields are private.
impl DeserializeStruct for JsonStructAccess
fn next_field<S: FieldSchema>(&mut self) -> Result<Option<i32>, DeserializeError>
fn value<T: Deserialize>(&mut self) -> Result<T, DeserializeError>
fn skip(&mut self) -> Result<(), DeserializeError>
fn end(&mut self) -> Result<(), DeserializeError>
pub struct JsonVariantAccess
Fields are private.
impl DeserializeVariant for JsonVariantAccess
fn variant_name(&mut self) -> Result<String, DeserializeError>
fn disc(&mut self) -> Result<i32, DeserializeError>
fn payload<T: Deserialize>(&mut self) -> Result<T, DeserializeError>
fn is_unit(&mut self) -> Result<bool, DeserializeError>
fn end(&mut self) -> Result<(), DeserializeError>
pub struct CanonicalJsonSerializer
The JSON Canonicalization Scheme (RFC 8785) serializer behind
to_bytes_canonical. Integers past the f64 safe range keep the string form
the other serializers give them, as RFC 8785 §6 advises.
Fields are private.
impl Serializer for CanonicalJsonSerializer
fn serialize_i32(&mut self, v: i32) -> Result<(), SerializeError>
fn serialize_i64(&mut self, v: i64) -> Result<(), SerializeError>
fn serialize_u32(&mut self, v: u32) -> Result<(), SerializeError>
fn serialize_u64(&mut self, v: u64) -> Result<(), SerializeError>
fn serialize_i128(&mut self, v: i128) -> Result<(), SerializeError>
fn serialize_u128(&mut self, v: u128) -> Result<(), SerializeError>
fn serialize_f32(&mut self, v: f32) -> Result<(), SerializeError>
fn serialize_f64(&mut self, v: f64) -> Result<(), SerializeError>
fn serialize_bool(&mut self, v: bool) -> Result<(), SerializeError>
fn serialize_char(&mut self, v: char) -> Result<(), SerializeError>
fn serialize_string<S: AsStrSlice>(&mut self, v: S) -> Result<(), SerializeError>
fn serialize_bytes(&mut self, v: ByteSlice) -> Result<(), SerializeError>
fn serialize_null(&mut self) -> Result<(), SerializeError>
fn begin_seq(&mut self, len: i32) -> Result<CanonicalSeqSerializer, SerializeError>
fn begin_map(&mut self, len: i32) -> Result<CanonicalMapSerializer, SerializeError>
fn begin_struct<S: AsStrSlice>(&mut self, name: S, fields: i32) -> Result<CanonicalStructSerializer, SerializeError>
fn serialize_unit_variant<S: AsStrSlice, S1: AsStrSlice>(&mut self, type_name: S, variant_name: S1, disc: i32) -> Result<(), SerializeError>
fn begin_variant<S: AsStrSlice, S1: AsStrSlice>(&mut self, type_name: S, variant_name: S1, disc: i32) -> Result<CanonicalVariantSerializer, SerializeError>
pub struct CanonicalSeqSerializer
Fields are private.
impl SerializeSeq for CanonicalSeqSerializer
fn element<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct CanonicalMapSerializer
Each entry is a key, unescaped, and its encoded value.
Fields are private.
impl SerializeMap for CanonicalMapSerializer
fn key<T: Serialize>(&mut self, key: &T) -> Result<(), SerializeError>
fn value<T: Serialize>(&mut self, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct CanonicalStructSerializer
Fields are private.
impl SerializeStruct for CanonicalStructSerializer
fn field<T: Serialize, S: AsStrSlice>(&mut self, name: S, value: &T) -> Result<(), SerializeError>
fn end(&mut self) -> Result<(), SerializeError>
pub struct CanonicalVariantSerializer
Fields are private.
