Expand description
§JsonTape
A minimalistic, allocator-aware JSON parser in pure Rust, offered in two complementary flavors that share one strict, RFC 8259-conformant scanner.
Jsonis an owned, mutable document and the default. Strings are eagerly unescaped into the document’s allocator at parse time, soJson::as_strneeds no source and the tree can be freely edited or built from scratch. Produce one withparseorparse_in.JsonViewis an immutable, zero-copy document. String values and object keys are kept asSpans into the original source rather than decoded, so parsing copies nothing, and lookups compare against those still-escaped spans with an escape-aware, allocation-free comparison. Produce one withvieworview_in.
Both containers allocate through any allocator_api2::alloc::Allocator, so the whole document can live in a bump
arena and free in one step.
use jsontape::parse;
let document = parse(br#"{ "metric": "ip", "nodes": 20000000, "peers": [1, 2, 3] }"#).unwrap();
// Navigate with indexing; a miss anywhere in the chain yields Null, not a panic.
assert_eq!(document["metric"].as_str(), Some("ip"));
assert_eq!(document["nodes"].as_u64(), Some(20_000_000));
assert_eq!(document["peers"][0].as_u64(), Some(1));
assert!(document["absent"].is_null());§Reading a view without threading source
A JsonView resolves its spans against the source you parsed. Bind the two together with JsonView::bind to
get a Resolved cursor that reads strings and navigates by key or index with no source argument:
use jsontape::view_bound;
let source = br#"{ "a": { "b": [10, 20] } }"#;
let document = view_bound(source).unwrap();
assert_eq!(document.get("a").get("b").get(1).as_u64(), Some(20));§Beyond parsing
- Serialize any document back to compact or pretty JSON with
to_string/Json::to_string_pretty, orJsonView::to_json_string. - Navigate with
Json::get, the[]operator, or an RFC 6901Json::pointer. - Preserve numbers losslessly: an integer wider than 64 bits, or a value outside the
f64range, is kept as its exact text (Json::as_number_str). - Emit incrementally without a document, writing one value at a time through
write_escaped_strandwrite_number— the same escaping and number spelling the serializer uses. - Configure the nesting limit and duplicate-key policy through
ParseOptionsand the*_withparsers. - Diagnose failures with a categorized
JsonError; resolve a fault to a line and column withJsonError::location.
§Cargo features
std(default) — enables thestd::error::Errorimpl; without it the crate isno_std(still requiringalloc).serde—serde::Serialize/serde::Deserializefor the document types plusto_value/from_valuefor converting to and from any serde type without a text round trip.
Structs§
- Array
Body - The backing storage for a
Json::Array: its elements plus optional comment trivia. With no commentstriviaisNoneand adds no heap allocation. It dereferences to the elementVec, so it indexes, iterates, and pushes like one —array.len(),array[0],for item in &arrayall work. - Bound
Json View - A zero-copy
JsonViewpermanently paired with the source it was parsed from. Prefer this type when exposing a view beyond the immediate parse site: its navigation and serialization APIs cannot accidentally receive a mismatched source slice. - Comment
- A comment preserved from JSON5 source, attached to a container element in the owned
Jsontree. The zero-copyJsonViewnever carries comments. - Format
Options - Controls how a document is rendered back to JSON text.
- Json
String - An owned, decoded UTF-8 string used for keys and string values in
Json. Its bytes are always valid UTF-8, soJsonString::as_strnever fails. - Location
- A resolved source position: byte offset plus 1-based line and column. The column counts bytes since the last newline.
- Object
Body - The backing storage for a
Json::Object: its(key, value)entries plus optional comment trivia. LikeArrayBody, it dereferences to the entryVecand carries no heap when there are no comments. - Parse
Limits - Optional resource limits for parsing untrusted documents. Limits other than nesting depth are disabled by default, so valid in-memory JSON remains accepted unless an application opts into a bounded profile.
- Parse
Options - Knobs for a parse: the nesting limit, the duplicate-key policy, and a set of opt-in lenient extensions toward JSON5.
Every lenient flag defaults to
falseso the default is strict RFC 8259; enable them individually, or start from thejsoncorjson5preset. Build fromParseOptions::defaultand adjust, then pass to a*_withparser. - Resolved
- A
JsonViewnode paired with thesourceit was parsed from, so string values resolve and keyed navigation work without threadingsourcethrough every call.Copy, so it chains freely:view.bind(src).get("a").get(0). - Span
- A span into the source bytes: a byte offset and a length. String values and object keys are stored this way, undecoded, so parsing copies nothing.
Enums§
- Comment
Style - Whether a preserved comment was written as a
//line or/* */block comment. - Duplicate
Keys - How to handle repeated keys within a single object.
- Indent
- Indentation style for pretty-printing: a fixed number of spaces per nesting level, or a single tab per level.
- Json
- An owned, mutable JSON document. Unlike
JsonView, strings are decoded at parse time, soJson::as_strneeds no source and the tree can be edited freely. Numbers keep their width past the2^53float boundary. - Json
Error - Why parsing failed. No code path panics on bad input.
- Json
View - An immutable JSON document that borrows its text from the parsed source. String values and object keys are stored as
Spans, so nothing is copied; resolve them against the samesourceyou parsed. Numbers keep their width, so large integers survive past the2^53float boundary. - Syntax
Kind - What kind of syntax fault occurred. Non-exhaustive so new categories can be added without a breaking change.
Traits§
- Lookup
- Types that can index a
Jsonvalue: a&strobject key or ausizearray position. PowersJson::get,Json::get_mut, and the infixcore::ops::Indexoperators. - Resolve
Key - A key or index that resolves a child of a
Resolvedcursor: a&strobject key (escape-aware) or ausizearray position.
Functions§
- from_
value - Deserializes any
T: Deserializedirectly from a borrowedJson. Strings are borrowed from the document, so&strfields need no copy. - parse
- Parses
sourceinto an owned, mutableJsonon the global heap. - parse_
in - Parses
sourceinto an owned, mutableJsonallocated inallocator, decoding every string’s escapes. The result borrows nothing fromsource. - parse_
in_ with - Parses
sourceinto an owned, mutableJsonallocated inallocator, underoptions. The result borrows nothing fromsource. - parse_
with - Parses
sourceinto an owned, mutableJsonon the global heap underoptions. - to_
value - Serializes any
T: Serializeinto an ownedJsonon the global heap, without going through a text representation. - unescape_
into - Decodes a JSON string
spanfromsource, appending the resulting UTF-8 bytes tooutput. Spans produced by this crate’s parser are always well-formed; a hand-built or mismatched span is reported, never panicked on. - view
- Parses
sourceinto an immutableJsonViewon the global heap. - view_
bound - Parses a source-bound, zero-copy document on the global heap. Unlike
view, the returned value retains its source reference and therefore cannot be navigated or serialized with a mismatched byte slice. - view_in
- Parses
sourceinto an immutableJsonViewallocated inallocator. Spans in the result are offsets intosource, so keepsourcealive. - view_
in_ bound - Parses a source-bound, zero-copy document with
allocator. - view_
in_ bound_ with - Parses a source-bound, zero-copy document with
allocatorunderoptions. - view_
in_ with - Parses
sourceinto an immutableJsonViewallocated inallocator, underoptions. Spans in the result are offsets intosource. - view_
with - Parses
sourceinto an immutableJsonViewon the global heap underoptions. - write_
escaped_ str - Writes
textas a quoted JSON string, escaping what the grammar requires. - write_
number - Writes a finite JSON number straight to
writer. Non-finite floats becomenull, and integral floats keep a trailing.0so their type survives a round trip.f64’s formatter never uses exponent notation, so writing directly and appending.0when integral needs no intermediate buffer. Public alongsidewrite_escaped_str, for the same incremental callers.