Skip to main content

Crate jsonx_lib

Crate jsonx_lib 

Source
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

  1. parse, from_str, and to_string (plus parse_bytes, from_bytes, to_string_pretty, and to_string_with): one call each, default budgets, duplicate keys refused.
  2. Parser: the same with your own Limits, DuplicateKeys policy, and Numbers option, kept as a const and reused.
  3. Reader: the document as a stream of Events, with read_raw to keep a value as its source text, read_value to build one part of it, decode to read one part as a type, and find_pointer to go straight to one value. StreamReader is the same reader over input that arrives in chunks; both read sequences of documents (NDJSON) on request.
  4. Typed values: FromJson reads a type from a Reader, borrowing strings from the input; ToJson writes a type through a ValueWriter, building nothing. Both are implemented by hand (or by the json_struct! macro for plain structs): no derive, no reflection. Errors are DecodeErrors: what, at which byte, and where (a JSON Pointer path).
  5. Writer: a push writer that takes events, checked as it goes, into a String, an io::Write, or a fmt::Write, in any Format.

§What it guarantees

  • RFC 8259 grammar. Everything outside the grammar is refused with an Error that 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 default DuplicateKeys::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 Number keeps 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 FromJson or ToJson impl 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): adds to_writer, to_writer_pretty, to_writer_with, Writer::io, StreamReader::read_from, and the HashMap/HashSet impls of the typed traits. Without it the crate is no_std and needs only alloc.

Macros§

json
Builds a Value from JSON-like syntax.
json_struct
Implements ToJson and FromJson for a struct whose fields map one to one onto object members.

Structs§

Array
A JSON array: a list of values in document order.
ArrayReader
Reads the items of an array one by one; from Reader::read_array.
ArrayWriter
Adds the items of an array being written; see ValueWriter::array.
DecodeError
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, from Object::iter.
IterMut
An iterator over an Object’s members with mutable values, from Object::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.
ObjectReader
Reads the members of an object one by one; from Reader::read_object.
ObjectWriter
Adds the members of an object being written; see ValueWriter::object.
OccupiedEntry
A member that is there; see Entry.
Parser
A configured parser: Limits and a DuplicateKeys policy.
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 Event at a time, building nothing.
StreamReader
A pull reader over input that arrives in pieces: bytes go in with feed as they arrive, events come out as soon as they are complete.
VacantEntry
A member that is not there; see Entry.
ValueWriter
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 ValueWriter wrote its value: what ToJson::to_json returns.

Enums§

DecodeErrorKind
What went wrong reading a typed value; see DecodeError.
DuplicateKeys
What to do when an object names the same key twice.
Entry
One member of an Object, there or not; from Object::entry.
ErrorKind
The kinds of Error.
Event
One step through a document, from Reader::next_event.
Kind
Which of JSON’s six kinds of value a Value is.
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.
PathSegment
One step of the path to a value: an object member’s key, or an array item’s index.
Step
The answer of a StreamReader call: ready, or waiting for more input.
Value
A JSON value, borrowing from the text it was parsed from.
WriteError
Why a Writer call was refused.

Traits§

FromJson
A type that reads itself from JSON, straight from a Reader.
FromJsonKey
A type usable as a JSON object key, for FromJson on maps.
ToJson
A type that writes itself as JSON, straight into the output.
ToJsonKey
A type usable as a JSON object key, for ToJson on maps.

Functions§

from_bytes
Reads bytes, which must be UTF-8, as one T; see from_str.
from_str
Reads text as one T (FromJson), with the default Limits and duplicate keys refused. The whole text must be that one value.
from_value
Reads an already built Value as a T, 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. See Parser::parse_bytes.
to_string
Serializes value as compact JSON: no whitespace at all.
to_string_pretty
Serializes value as 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 value in the given Format.
to_value
Builds a Value from any ToJson type, by writing it and reading it back (members exactly as written, duplicates included).
to_writerstd
Writes value as compact JSON to an io::Write, through a buffer of a few kilobytes, so a large document is never held as one string.
to_writer_prettystd
Writes value as indented JSON (see to_string_pretty) to an io::Write, through a buffer of a few kilobytes.
to_writer_withstd
Writes value in the given Format to an io::Write, through a buffer of a few kilobytes.
write_string
Appends text to out as a JSON string literal, quotes included.
write_value
Appends value to out as compact JSON (see to_string). Reusing one buffer across documents avoids an allocation per document.
write_value_pretty
Appends value to out as indented JSON (see to_string_pretty).
write_value_with
Appends value to out in the given Format.