The model
The ways in, simplest first:
parse,from_str, andto_string: one call each, default budgets, duplicate keys refused.Parser: the same with your ownLimits,DuplicateKeyspolicy, andNumbersoption, defined once as aconst.Reader: the document as a stream ofEvents, withread_rawto keep a value as its exact source text,read_valueto build one part,decodeto read one part as a type, andfind_pointerto go straight to one value.StreamReaderis the same reader fed in chunks as input arrives. Both read sequences of documents (NDJSON) on request.- Typed values:
FromJsonreads your type from a reader andToJsonwrites it through a typed writer, with no tree in between. You implement them by hand (or letjson_struct!do it for a plain struct): no derive, no reflection. Errors say what, at which byte, and where (a JSON Pointer path). Writer: a push writer, checked as it goes, into aString, anio::Write, or afmt::Write, in anyFormat(indent width, HTML-safe, ASCII-only).
A parsed Value borrows from its input; Number keeps exact text with lazy conversion; Object keeps members in document order; RawValue keeps a validated value as text; json! builds values in code.
What it guarantees, and how each guarantee is checked:
| Guarantee | How it is held |
|---|---|
| The RFC 8259 grammar; everything outside it refused at the first byte that cannot continue a valid text. Lone surrogate escapes, and (by default) repeated keys, are refused by choice. | Property tests run random token soup and mutated documents through the crate and an independent strict reference parser written from the RFC grammar: verdict, value, and exact error offset agree. 234 JSONTestSuite-style cases written as data (73 accept, 127 refuse, 34 implementation-defined) pin the kind and offset of every refusal. |
| Every way of reading agrees: parse, events, raw slices, the incremental reader at any chunking, typed reads. | Properties compare the incremental reader with the complete one for every mix of calls and chunk boundaries, and every reading path's duplicate-key refusals with parse's. |
| Duplicate keys cannot smuggle a second value. | Refused by default on every reading path, compared after unescaping, in O(n log n); the documented JSON-RPC Reader loop sees the error at the object's }. Every policy is checked against a naive reference. |
| Written output parses back to the same value, in every format (for objects without repeated keys: the writers do not check keys for repeats). | Round-trip properties over arbitrary documents, compact, pretty, indented, HTML-safe, and ASCII-only, checked by both parsers; typed output matches the Value output it stands for. |
| No string can change the structure of the output. | Arbitrary strings (rich in quotes, backslashes, control characters, U+2028/U+2029) written as values and keys always read back, under the reference parser, as exactly themselves. |
Budgets refuse before allocating; one read call (parse, read_value, decode), tree or typed value, holds at most about max_memory (64 MiB by default). |
A counting allocator measures peak heap: an 8 MiB string over a 1 KiB budget is refused with under 1 KiB allocated; over-size input with none; five hostile document shapes (flat, nested, pairs, members, escapes) stay within max_memory under the defaults. |
| No stack overflow, no panic. | A million levels of nesting parse, write, transcode, clone, compare, and drop on a thread with a 256 KiB stack. Five cargo-fuzz targets cover every reading entry point with these oracles (no counterexample in about 4.0 M runs of the smoke pass), and the same checks run on arbitrary bytes in cargo test on every platform. |
Installation
[]
= "0.5"
Without the standard library:
[]
= { = "0.5", = false }
Quick start
use ;
let doc = parse?;
assert_eq!;
assert_eq!;
assert!; // indexing never panics
let reply = json!;
assert_eq!;
let err = parse.unwrap_err;
assert_eq!;
# Ok::
Your own types, no serde
use Cow;
use ;
// A plain struct: one line writes both impls.
json_struct!;
// Or by hand, for full control.
let text = r#"{"uri": "file:///a.rs", "position": {"line": 3, "character": 14}}"#;
let loc: Location = from_str?;
assert!; // borrowed from `text`
assert_eq!;
let bad = r#"{"uri": "x", "position": {"line": "3", "character": 0}}"#;
let err = .err.map;
assert_eq!;
# Ok::
Budgets and duplicate keys
use ;
const WIRE: Parser = new
.limits
.duplicate_keys;
let err = WIRE.parse.unwrap_err;
assert_eq!;
let err = WIRE.parse.unwrap_err;
assert_eq!;
Reading a message without building a tree
use ;
let message = r#"{"jsonrpc": "2.0", "id": 4, "method": "hover", "params": {"line": 3}}"#;
let mut reader = new;
let = ;
assert_eq!;
while let Some = reader.next_event?
reader.finish?;
assert_eq!;
assert_eq!;
// A repeated member never reaches the end of that loop: the reader refuses
// the object at its `}`, as `parse` does.
let mut reader = new;
reader.next_event?;
while let Ok = reader.next_event
assert!;
# Ok::
Input as it arrives, output as it goes
use ;
// NDJSON from a socket, fed in whatever pieces arrive.
let mut stream = new.documents;
let mut out = Stringnew;
let mut writer = new;
writer.begin_array?;
for chunk in
stream.end_input;
writer.end_array?;
writer.finish?;
assert_eq!;
# Ok::
Performance
Measured against 0.2.0 on the same machine (Windows x86_64, Rust 1.99), with paired samples so load hits both versions alike; time is 0.5's over 0.2's, 10th to 90th percentile:
| Input | parse |
Reader events (duplicate keys refused) |
|---|---|---|
| An LSP request's params (~110 bytes) | 0.80-0.93, 5 allocations (0.2: 7) | 0.77-0.81, no allocation |
| A whole LSP request (~175 bytes) | 0.82-0.97 | 0.72-0.97 |
| A 1 MiB LSP document | 0.80-1.02 | 0.87-1.18 |
On the 1 MiB benchmark document (cargo bench --bench bench): parse about
220 MiB/s, events about 510 MiB/s, read_raw about 610 MiB/s, to_string
about 1.05 GiB/s, typed decoding into structs about 300 MiB/s, and the
incremental reader about 395 MiB/s. Typed decoding of a small request
takes 2.3 to 2.6 times as long as serde_json's derive (median about 2.5
times) and allocates nothing. Method and every
number: the release notes.
0.5.1 made writing faster without changing a byte of output: typed
structs in 0.56 of 0.5.0's time, pretty output in 0.72, floats in about a
third; metrics-lib's JSON snapshot is written in about 0.75 of
serde_json's time. The 0.5.1 release notes.
Documentation
- API reference: every public item, with examples, and a guide to moving a JSON-RPC server off serde_json.
- Release notes for 0.5.2, 0.5.1, 0.5.0, and 0.2.0.
- Roadmap and engineering directives.
- Examples:
cargo run --example quick_start,rpc_envelope,typed_lsp.
Contributing
See dev/DIRECTIVES.md for engineering standards and the definition of done. Before a PR: cargo fmt --all, cargo clippy --all-targets --all-features -- -D warnings, and cargo test --all-features must be clean.