babbel_json
Version 0.2.0 — A lightweight, modular JSON toolkit for Rust with pluggable I/O sources/destinations, a simple in-memory Node tree, multiple serializers (JSON, YAML, XML, Bencode, TOML), and no_std support. Designed for small binaries, predictable behavior, and easy embedding.
- Core
Nodetype representing JSON structures - Parser to build Node trees from streams, strings, or byte slices
- Zero-allocation JSON validation
- Stringifiers to JSON, YAML, XML, Bencode, and TOML
- Performance-optimized serialization with lazy escaping and arena allocation
- File and in-memory buffer I/O abstractions
- Pretty-printing utilities
- Line-delimited JSON (JSON Lines / NDJSON /
.jsonl) streaming reader and writer - JSON Pointer (RFC 6901), JSON Patch (RFC 6902), and JSON Merge Patch (RFC 7386)
- JSON Schema validation (Draft 7 subset)
- JSON5 comment stripping
json!macro for ergonomic Node construction- Unicode-aware file helpers (BOM detection/handling)
no_stdcompatible with theallocfeature
Minimum supported Rust version: 1.88.0
Features at a glance
NodeandNumerictypes for representing all JSON values- Parse with
parse,from_str,from_bytes, orparse_with_config lines::JsonLinesReader— stream record-by-record without buffering entire filesvalidate_json— check syntax without building a Node tree- Streaming-friendly
ISource/IDestinationtraits FileSource/FileDestinationandBufferSource/BufferDestination- Pretty printer (
print) and optimized serializer (stringify_optimized) - Convert a
Nodeto alternate formats (YAML, XML, Bencode, TOML) - JSON Pointer navigation and mutation (
pointer_get,pointer_set,pointer_remove) - JSON Patch operations (
patch::apply_operation,patch::apply_patch) - JSON Merge Patch (
merge_patch::merge_patch) - JSON Schema validation (
schema::SchemaValidator) - JSON5 comment stripping (
parser::json5::strip_comments) json!macro for inline Node constructionParserConfigfor resource limits;ParseStatsfor profiling- Unicode file format detection and read/write helpers
Cargo features
| Feature | Default | Description |
|---|---|---|
std |
yes | Enables standard library support (includes alloc) |
alloc |
yes (via std) |
Enables heap allocation without full std |
file-io |
yes | FileSource, FileDestination, and Unicode file helpers |
format-yaml |
no | to_yaml encoder |
format-xml |
no | to_xml encoder |
format-bencode |
no | to_bencode encoder |
format-toml |
no | to_toml encoder |
json-pointer |
no | JSON Pointer, JSON Patch support |
no_std usage
Disable default features and enable alloc for embedded / bare-metal targets:
[]
= { = "0.2.0", = false, = ["alloc"] }
# Or within the workspace:
# babbel_json = { path = "crates/json", default-features = false, features = ["alloc"] }
Installation
Add to your Cargo.toml:
[]
= "0.2.0"
Or as a workspace path dependency:
[]
= { = "crates/json" }
All streaming I/O in babbel_json (FileSource, FileDestination, BufferSource, Buffer) is unified with and powered by babbel_core::io.
Embedding Guide
To embed this library in another Rust project:
- Add the path or version dependency as shown above.
- Import the required items in your code:
use ; - For comprehensive architecture and conversion pipelines across the Babbel ecosystem, refer to the Babbel Architecture Guide.
Quick start
Parse from a string or bytes
use ;
let node = from_str.unwrap;
let node = from_bytes.unwrap;
Stream Line-Delimited JSON (JSON Lines / NDJSON)
use ;
use SliceSource;
// 1. Batch parsing
let data = "{\"id\": 1}\n{\"id\": 2}\n";
let records = parse_json_lines.unwrap;
assert_eq!;
// 2. Stream-by-record iteration
let source = new;
let mut reader = new;
while let Some = reader.next_node
// 3. Serialization
let jsonl_output = to_json_lines.unwrap;
Build a Node with the json! macro
use ;
let value = json!;
assert_eq!;
assert_eq!;
Parse a file, then pretty-print to another file
use ;
use Path;
Build a Node in memory and stringify to a buffer
use ;
Validate JSON without allocating
use ;
let mut source = new;
let config = new;
assert!;
Parse with resource limits
use ;
let config = ParserConfig ;
let mut src = new;
let node = parse_with_config.unwrap;
Convert a Node to YAML / XML / Bencode
use ;
let node = Array;
let mut yaml = new;
to_yaml;
println!;
let mut xml = new;
to_xml;
println!;
let mut bencode = new;
to_bencode;
println!;
JSON Pointer (RFC 6901)
use ;
let mut doc = json!;
// Read a value
let name = pointer_get;
assert_eq!;
// Write a value
pointer_set.unwrap;
JSON Patch (RFC 6902)
use ;
let mut doc = json!;
let ops = vec!;
apply_patch.unwrap;
// doc is now {"a": 1, "c": 3}
JSON Merge Patch (RFC 7386)
use ;
let mut doc = json!;
let patch = json!;
merge_patch;
// doc is now {"a": 1, "b": 3, "c": 4}
JSON Schema validation
use ;
let schema = json!;
let validator = new;
assert!;
assert!; // missing "name"
JSON5 comment stripping
use strip_comments;
let input = r#"{
"name": "Alice", // single-line comment
/* multi-line
comment */
"age": 30
}"#;
let clean = strip_comments;
let node = from_str.unwrap;
Read/write text files with Unicode BOM handling
use ;
API overview
Version
version() -> &'static str
I/O
FileSource/FileDestination— file-backed I/O (requiresfile-iofeature)BufferSource/BufferDestination— in-memory I/O
Node model
Node:Object,Array,Str,Number(Numeric),Boolean,NoneNumeric:Integer(i64),UInteger(u64),Float(f64),Byte(u8),Int8(i8),Int16(i16),UInt16(u16),Int32(i32),UInt32(u32)
Parsing
parse(&mut Source) -> Result<Node, String>parse_with_config(&mut Source, &ParserConfig) -> Result<Node, String>from_str(&str) -> Result<Node, String>from_bytes(&[u8]) -> Result<Node, String>validate_json(&mut Source, &ParserConfig) -> Result<(), String>— zero-allocation syntax check
Stringifying
stringify(&Node, &mut Destination)stringify_pretty(...)— alias forprintprint(&Node, &mut Destination, indent, current_indent)— human-readable outputstringify_optimized(&Node, &mut Destination) -> Result<(), String>— lazy escaping, fast pathsstrip_whitespace(src, dst)— compact whitespace removal
Alternative format encoders (feature-gated)
to_yaml(&Node, &mut Destination)— requiresformat-yamlto_xml(&Node, &mut Destination)— requiresformat-xmlto_bencode(&Node, &mut Destination)— requiresformat-bencodeto_toml(&Node, &mut Destination)— requiresformat-toml
JSON Pointer (requires json-pointer)
pointer_get(&Node, &str) -> Option<&Node>pointer_get_mut(&mut Node, &str) -> Option<&mut Node>pointer_set(&mut Node, &str, Node) -> Result<(), String>pointer_remove(&mut Node, &str) -> Result<Node, String>
JSON Patch (requires json-pointer)
nodes::patch::apply_operation(&mut Node, &PatchOp) -> Result<(), PatchError>nodes::patch::apply_patch(&mut Node, &[PatchOp]) -> Result<(), PatchError>PatchOp:Add,Remove,Replace,Move,Copy,Test
JSON Merge Patch
nodes::merge_patch::merge_patch(&mut Node, &Node)
JSON Schema validation
nodes::schema::SchemaValidator::new(schema: Node) -> SchemaValidatorSchemaValidator::validate(&Node) -> Result<(), Vec<ValidationError>>
JSON5
parser::json5::strip_comments(&str) -> String
Parser configuration and profiling
ParserConfig::new()— conservative limits suitable for embedded systemsParserConfig::unlimited()— no limitsParseStats— peak depth, node count, string bytes, estimated memory, parse time
Unicode-aware file helpers (requires file-io)
detect_format(path) -> Result<Format, String>read_file_to_string(path) -> Result<String, String>write_file_from_string(path, &str, Format) -> Result<(), String>
json! macro
json!(null),json!(true),json!(42),json!("text"),json!([...]),json!({...})
Performance features
Several alloc-gated modules provide lower-overhead alternatives for hot paths:
parser::arena— arena allocator to reduce per-node heap allocationsparser::fast— SIMD-friendly fast parsing utilitiesparser::sso— Small String Optimization for short keys and valuesstringify::optimized::stringify_optimized— lazy escaping and batch writes
Design goals
- Small, explicit API focused on Node-based manipulation
- Works with streams and simple abstractions
- Deterministic and predictable output
no_stdcompatible for embedded and constrained targets- Easy to integrate for CLI tools, small services, and firmware
Roadmap ideas
- Optional parse/stringify options (e.g., key sorting, non-ASCII escaping)
- Streaming parser and incremental writer
- Canonical JSON and stable hashing
- Optional serde interop and async I/O
If you're interested in any of these, contributions are welcome.
Conformance Test Results
babbel_json is continuously tested against the official JSONTestSuite for RFC 8259 compliance.
| Suite Category | Focus Area | Total Cases | Passed | Failed | Pass Rate | Status |
|---|---|---|---|---|---|---|
Parsing (y_) |
Mandatory acceptance of valid JSON & surrogate pairs | 95 | 95 | 0 | 100.0% | PASSED |
Parsing (n_) |
Mandatory rejection of malformed syntax & control chars | 188 | 188 | 0 | 100.0% | PASSED |
Parsing (i_) |
Implementation-defined edge cases & huge numbers | 35 | 35 | 0 | 100.0% | PASSED |
| Transform | Key duplicates, escaped nulls, normalization | 22 | 22 | 0 | 100.0% | PASSED |
| OVERALL | Full Official JSONTestSuite Corpus | 340 | 340 | 0 | 100.0% | VERIFIED |
Running the Conformance Runner
# 1. Fetch test fixtures on demand
# On Linux/macOS: ./scripts/fetch_json_test_suite.sh
# 2. Run the 340 test cases
Documentation
See the Documentation Hub for complete guides:
- JSON Conformance Guide (RFC 8259)
- Architecture Guide
- Development Guide
- Contributing Guidelines
- Code of Conduct
- Embedded Systems Guide
- Security Policy
License
This project is licensed under the terms of the LICENSE file included in the repository.
Contributing
- Open issues for bugs and feature requests
- PRs with tests are welcome
- Please format and lint your code before submitting
Support
If you run into issues or have questions, please open an issue in the repository.