Expand description
§jsonx_lib
Strict RFC 8259 JSON: a parser that borrows from its input, pull and
incremental readers, typed reading and writing through hand-written
FromJson and ToJson impls, and deterministic writers, with
budgets that refuse hostile input before it costs memory. No
dependencies; no_std with alloc.
§Quick start
use jsonx_lib::{json, json_struct, parse, to_string};
// A document as a tree.
let doc = parse(r#"{"name": "jsonx", "version": [0, 5, 0], "stable": false}"#)?;
assert_eq!(doc["name"], "jsonx");
assert_eq!(doc["version"][1].as_u64(), Some(5));
// Or straight into your own types, and back, with no tree in between.
struct Position { line: u32, character: u32 }
json_struct!(Position { line, character });
let p: Position = jsonx_lib::from_str(r#"{"line": 3, "character": 14}"#)?;
assert_eq!((p.line, p.character), (3, 14));
assert_eq!(to_string(&p), r#"{"line":3,"character":14}"#);
let reply = json!({ "ok": true, "items": [1, 2, 3] });
assert_eq!(to_string(&reply), r#"{"ok":true,"items":[1,2,3]}"#);§The ways in
parse,from_str, andto_string(plusparse_bytes,from_bytes,to_string_pretty, andto_string_with): one call each, default budgets, duplicate keys refused.Parser: the same with your ownLimits,DuplicateKeyspolicy, andNumbersoption, kept as aconstand reused.Reader: the document as a stream ofEvents, withread_rawto keep a value as its source text,read_valueto build one part of it,decodeto read one part as a type, andfind_pointerto go straight to one value.StreamReaderis the same reader over input that arrives in chunks; both read sequences of documents (NDJSON) on request.- Typed values:
FromJsonreads a type from aReader, borrowing strings from the input;ToJsonwrites a type through aValueWriter, building nothing. Both are implemented by hand (or by thejson_struct!macro for plain structs): no derive, no reflection. Errors areDecodeErrors: what, at which byte, and where (a JSON Pointer path). Writer: a push writer that takes events, checked as it goes, into aString, anio::Write, or afmt::Write, in anyFormat.
§What it guarantees
- RFC 8259 grammar. Everything outside the grammar is refused with an
Errorthat names the first byte at which the input stops being valid. Two grammatical inputs are refused by choice: unpaired UTF-16 surrogate escapes, which decode to no Unicode text, and (under the defaultDuplicateKeys::Error) objects that repeat a key, on every way of reading. - Borrowing. Strings without escapes and every number are slices of the input; a string with escapes is decoded once into a buffer no larger than its escaped source text.
- Exact numbers. A
Numberkeeps its text; conversion to a Rust number happens when asked and never rounds silently into an integer. - Budgets. Depth, input size, string length, number length, value
count, and the memory one read holds for what it builds (a tree or
typed values) are all bounded
(
Limits), each checked before the memory it guards is used. - No recursion on depth. Parsing, the readers, writing, cloning,
comparing, and hashing loop over explicit stacks; dropping recurses at
most a fixed 32 levels. A million levels of nesting cannot overflow the
stack. (A
FromJsonorToJsonimpl for a recursive type of your own recurses; the depth budget bounds that on the reading side.) - Round trip. Written output parses back to an equal value (for
objects without repeated keys, which the writers do not check), in every
Format, and no string can break out of its quotes (write_string). - No panics on any input, and
#![forbid(unsafe_code)].
§Feature flags
std(default): addsto_writer,to_writer_pretty,to_writer_with,Writer::io,StreamReader::read_from, and theHashMap/HashSetimpls of the typed traits. Without it the crate isno_stdand needs onlyalloc.
Macros§
- json
- Builds a
Valuefrom JSON-like syntax. - json_
struct - Implements
ToJsonandFromJsonfor a struct whose fields map one to one onto object members.
Structs§
- Array
- A JSON array: a list of values in document order.
- Array
Reader - Reads the items of an array one by one; from
Reader::read_array. - Array
Writer - Adds the items of an array being written; see
ValueWriter::array. - Decode
Error - Why a typed value could not be read: what went wrong, at which byte, and where in the document.
- Error
- Why a document was rejected, and where.
- Format
- How the writers lay out and escape their output.
- Iter
- An iterator over an
Object’s members, fromObject::iter. - IterMut
- An iterator over an
Object’s members with mutable values, fromObject::iter_mut. - Limits
- Budgets on the work and memory a document may cost.
- Number
- A JSON number, kept as the exact text of the document.
- Object
- A JSON object: its members in document order.
- Object
Reader - Reads the members of an object one by one; from
Reader::read_object. - Object
Writer - Adds the members of an object being written; see
ValueWriter::object. - Occupied
Entry - A member that is there; see
Entry. - Parser
- A configured parser:
Limitsand aDuplicateKeyspolicy. - RawValue
- One complete JSON value kept as its exact source text: validated once, then stored, compared, forwarded, or read later.
- Reader
- A pull parser: reads a document one
Eventat a time, building nothing. - Stream
Reader - A pull reader over input that arrives in pieces: bytes go in with
feedas they arrive, events come out as soon as they are complete. - Vacant
Entry - A member that is not there; see
Entry. - Value
Writer - Writes one JSON value; see
ToJson. - Writer
- A push writer: a document written one event at a time, checked as it goes.
- Written
- Proof that a
ValueWriterwrote its value: whatToJson::to_jsonreturns.
Enums§
- Decode
Error Kind - What went wrong reading a typed value; see
DecodeError. - Duplicate
Keys - What to do when an object names the same key twice.
- Entry
- One member of an
Object, there or not; fromObject::entry. - Error
Kind - The kinds of
Error. - Event
- One step through a document, from
Reader::next_event. - Kind
- Which of JSON’s six kinds of value a
Valueis. - Nullable
- A member that may be absent,
null, or a value, keeping the three apart. - Numbers
- How typed reads (
FromJson) of integers treat a number written as a fraction or with an exponent. - Path
Segment - One step of the path to a value: an object member’s key, or an array item’s index.
- Step
- The answer of a
StreamReadercall: ready, or waiting for more input. - Value
- A JSON value, borrowing from the text it was parsed from.
- Write
Error - Why a
Writercall was refused.
Traits§
- From
Json - A type that reads itself from JSON, straight from a
Reader. - From
Json Key - A type usable as a JSON object key, for
FromJsonon maps. - ToJson
- A type that writes itself as JSON, straight into the output.
- ToJson
Key - A type usable as a JSON object key, for
ToJsonon maps.
Functions§
- from_
bytes - Reads
bytes, which must be UTF-8, as oneT; seefrom_str. - from_
str - Reads
textas oneT(FromJson), with the defaultLimitsand duplicate keys refused. The whole text must be that one value. - from_
value - Reads an already built
Valueas aT, for a type that owns its data. - parse
- Parses one JSON document with the default
Limits, refusing duplicate keys. - parse_
bytes - Parses one JSON document from bytes, which must be UTF-8, with the default
Limits. SeeParser::parse_bytes. - to_
string - Serializes
valueas compact JSON: no whitespace at all. - to_
string_ pretty - Serializes
valueas indented JSON: two spaces per level, one member or item per line,": "after keys, empty containers as[]and{}, and no trailing newline. - to_
string_ with - Serializes
valuein the givenFormat. - to_
value - Builds a
Valuefrom anyToJsontype, by writing it and reading it back (members exactly as written, duplicates included). - to_
writer std - Writes
valueas compact JSON to anio::Write, through a buffer of a few kilobytes, so a large document is never held as one string. - to_
writer_ pretty std - Writes
valueas indented JSON (seeto_string_pretty) to anio::Write, through a buffer of a few kilobytes. - to_
writer_ with std - Writes
valuein the givenFormatto anio::Write, through a buffer of a few kilobytes. - write_
string - Appends
texttooutas a JSON string literal, quotes included. - write_
value - Appends
valuetooutas compact JSON (seeto_string). Reusing one buffer across documents avoids an allocation per document. - write_
value_ pretty - Appends
valuetooutas indented JSON (seeto_string_pretty). - write_
value_ with - Appends
valuetooutin the givenFormat.