cjson-bindings
Safe Rust bindings for the cJSON library - a lightweight JSON parser in C.
Overview
cjson-bindings provides idiomatic, safe Rust wrappers around the cJSON C library, offering:
- Safe API: Memory-safe wrappers with automatic resource management (RAII)
- Type-safe operations: Strong typing with
Resulttypes for error handling - JSON Pointer support (RFC6901): Navigate JSON documents using JSON Pointer syntax
- JSON Patch support (RFC6902): Generate and apply JSON patches
- JSON Merge Patch support (RFC7386): Generate and apply merge patches
- Serialization/Deserialization: Full support for
#[derive(Serialize, Deserialize)]with osal-rs-serde integration - no_std compatible: Suitable for embedded systems with built-in allocator and panic handler
Embedded & no_std Support
The library is designed for embedded systems and supports no_std environments:
- Global Allocator: Uses C's
malloc/freevia FFI - Default Panic Handler: Provides a simple infinite loop panic handler
- Custom Panic Handler: Use the
disable_panicfeature to provide your own
Cargo Features
std: Enables standard library support (required for tests)disable_panic: Disables both the default allocator and panic handler, allowing you to provide your ownosal_rs: Enables integration with osal-rs and osal-rs-serde for automatic serialization/deserialization with#[derive]macros
Example with custom allocator and panic handler:
[]
= { = "0.6.0", = ["disable_panic"] }
Then provide your own in your application:
use ;
;
unsafe
static ALLOCATOR: MyAllocator = MyAllocator;
!
Features
Core JSON Operations
- Parse and print JSON with automatic memory management
- Create and manipulate JSON objects, arrays, strings, numbers, booleans, and null values
- Type checking and value retrieval with compile-time safety
- Deep cloning and comparison
Advanced Features
- JSON Pointer (RFC6901): Navigate JSON structures using paths like
/foo/bar/0 - JSON Patch (RFC6902): Generate and apply patch operations (add, remove, replace, move, copy, test)
- JSON Merge Patch (RFC7386): Simpler patch format for common use cases
- Sorting object keys alphabetically
Serialization & Deserialization (with osal_rs feature)
When the osal_rs feature is enabled, cjson-bindings provides full integration with the osal-rs-serde framework for automatic serialization and deserialization:
- Derive Macros: Use
#[derive(Serialize, Deserialize)]on your structs - Type-safe: Compile-time guarantees for data conversion
- Memory-efficient: Direct JSON creation/parsing without intermediate allocations
- Nested structures: Full support for complex nested data structures
- Easy API: Simple
to_json()andfrom_json()functions
Supported Types
Primitives
- Integers:
u8,i8,u16,i16,u32,i32,u64,i64,u128,i128 - Floats:
f32,f64 - Boolean:
bool
Compound Types
- Arrays:
[T; N]for any serializable type T - Vec:
Vec<T>for dynamic arrays - String:
Stringand&str - Bytes:
&[u8](serialized as hexadecimal string)
Custom Types
- Any struct with
#[derive(Serialize, Deserialize)] - Nested struct composition fully supported
JSON Format & Type Mapping
The JSON serializer/deserializer maps Rust types to JSON as follows:
bool → JSON boolean (true/false)
integers → JSON number (converted to f64)
floats → JSON number
String/str → JSON string
&[u8] → JSON string (hexadecimal representation)
Vec<T> → JSON array
[T; N] → JSON array
struct → JSON object
Note: All integer types (u8-u128, i8-i128) are converted to/from JSON numbers (f64). Be aware of potential precision loss for values larger than 2^53 (JavaScript number limitations).
Installation
Add to your Cargo.toml:
Basic Usage (JSON parsing only)
[]
= "0.6.0"
With Serialization Support
For automatic serialization/deserialization with derive macros:
[]
= { = "0.6.0", = ["osal_rs"] }
For Embedded Systems (no_std)
[]
= { = "0.6.0", = false }
With Custom Allocator and Panic Handler
[]
= { = "0.6.0", = ["disable_panic"] }
Available features:
std: Enables standard library support (default: disabled)disable_panic: Disables default allocator and panic handler (default: disabled)osal_rs: Enables osal-rs-serde integration for serialization (default: disabled)
Usage
Basic Example
use ;
Serialization & Deserialization Examples (with osal_rs feature)
Basic Struct Serialization
use ;
use ;
Nested Structs
use ;
use ;
Arrays and Vectors
use ;
use ;
use Vec;
Complex Embedded System Example
use ;
use ;
JSON Pointer Example
use ;
let json = parse?;
// Navigate using JSON Pointer
let bob = get?;
println!; // "Bob"
JSON Patch Example
use ;
let mut original = parse?;
let patches = parse?;
// Apply patches
apply?;
println!;
// Output: {"name":"John","age":31,"city":"NYC"}
JSON Merge Patch Example
use ;
let mut target = parse?;
let patch = parse?;
// Apply merge patch
let result = apply?;
println!;
API Types
Main Types
CJson: Owned JSON value with automatic memory managementCJsonRef: Borrowed reference to a JSON value (non-owning)CJsonResult<T>: Result type for operations that can failCJsonError: Error enumeration for all possible errors
Utility Types
JsonPointer: JSON Pointer (RFC6901) operationsJsonPatch: JSON Patch (RFC6902) operationsJsonMergePatch: JSON Merge Patch (RFC7386) operationsJsonUtils: Additional utilities (e.g., sorting)
Serialization Types (with osal_rs feature)
JsonSerializer: Serializes Rust types to JSON formatJsonDeserializer: Deserializes JSON to Rust typesto_json<T>(&T) -> Result<String>: High-level serialization functionfrom_json<T>(&String) -> Result<T>: High-level deserialization function
Error Handling
All operations that can fail return CJsonResult<T>, which is a type alias for Result<T, CJsonError>:
Memory Safety
`` ensures memory safety through:
- RAII:
CJsonautomatically frees memory when dropped - No manual memory management: All allocations/deallocations are handled automatically
- Reference types:
CJsonRefprovides safe borrowing without ownership transfer - Clear ownership:
into_raw()for explicit ownership transfer when needed
Best Practices
1. Use Derive Macros for Serialization
Always prefer derive macros with the osal_rs feature for automatic serialization:
2. Handle Errors Appropriately
Always handle serialization/deserialization errors:
match to_json
3. Use Type-Safe Access
Prefer type-safe methods over raw pointer manipulation:
// Good
let value = json.get_object_item?.get_number_value?;
// Avoid
let ptr = json.as_ptr; // Manual pointer manipulation
4. Memory Management in Embedded Systems
For embedded systems, consider using custom allocator with disable_panic feature:
static ALLOCATOR: MyAllocator = MyAllocator;
!
5. Numeric Precision
Be aware of JSON number limitations (IEEE 754 double precision):
// Precise for values up to 2^53
let safe_value: u32 = 1_000_000;
// May lose precision
let large_value: u64 = 9_007_199_254_740_993; // > 2^53
6. Versioning for Compatibility
Add version fields for forward/backward compatibility:
Performance Considerations
JSON Number Precision
All Rust integer types are converted to JSON numbers (IEEE 754 double precision float):
- Safe range: Values up to ±2^53 (9,007,199,254,740,992) maintain exact precision
- Loss of precision: Larger integers may lose precision during serialization/deserialization
- Recommendation: For values > 2^53, consider using strings instead
Memory Usage
- Stack allocation: JSON structures are allocated on the heap via C's malloc
- Automatic cleanup: RAII ensures memory is freed when objects go out of scope
- Zero-copy parsing: String values reference the original JSON buffer when possible
Embedded Systems Optimization
For resource-constrained environments:
// Pre-calculate expected JSON size
const EXPECTED_SIZE: usize = 256;
// Use stack buffers where possible
let json_str = to_json.unwrap;
// Process immediately to free memory
process_json;
Comparison with Other Libraries
| Feature | cjson-bindings | serde_json | json | tinyjson |
|---|---|---|---|---|
| No-std support | ✅ Native | ✅ Via feature | ❌ | ✅ Native |
| Derive macros | ✅ (via osal_rs) | ✅ (via serde) | ❌ | ❌ |
| JSON Pointer (RFC6901) | ✅ Built-in | ✅ Via crate | ❌ | ❌ |
| JSON Patch (RFC6902) | ✅ Built-in | ✅ Via crate | ❌ | ❌ |
| JSON Merge Patch (RFC7386) | ✅ Built-in | ✅ Via crate | ❌ | ❌ |
| Binary size | Small | Medium | Small | Very small |
| Speed | Fast (C library) | Very fast | Medium | Medium |
| C library dependency | ✅ cJSON | ❌ | ❌ | ❌ |
| Memory allocator | C malloc | Rust | Rust | Rust |
| Embedded RTOS support | ✅ Excellent | ⚠️ Limited | ❌ | ⚠️ Limited |
| Learning curve | Easy | Moderate | Easy | Easy |
Choose cjson-bindings when:
- Working in embedded/RTOS environments with C interoperability
- Need RFC6901/6902/7386 support out of the box
- Prefer battle-tested C library (cJSON is widely used)
- Want simple, straightforward API
- Integrating with existing C/C++ codebase
Choose serde_json when:
- Pure Rust solution preferred
- Maximum performance is critical
- Need extensive ecosystem integration
- Working primarily with std
Choose tinyjson when:
- Minimal binary size is top priority
- Don't need advanced features
- Simple JSON parsing only
Dependencies
This crate links against the cJSON C library. You need to have cJSON installed or provide it as part of your build process.
License
This Rust wrapper is licensed under the GNU General Public License v3.0 (GPL-3.0).
The underlying cJSON library is licensed under the MIT License.
cJSON License
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
See LICENSE for the full GPL-3.0 license text and cJSON's license for details.
Testing
The library includes comprehensive unit tests covering all major functionality. To run the tests:
Or use the provided alias:
See TESTS.md for detailed test documentation and coverage information.
Test Requirements
- cJSON library installed on your system (
libcjsonandlibcjson_utils) - Standard library support (enabled via the
stdfeature for testing)
Running tests locally (linking cJSON built from source)
If you need to run the crate tests locally and link against a locally-built cJSON (useful for no_std embedded workflows where the project CMake already builds cJSON), follow these steps:
- Clone and build cJSON for the host:
- Run
cargo testwhile telling the Rust linker where to find the cJSON libraries (example assumes you built cJSON underbuild-host/cJSON/buildinside the project root):
LD_LIBRARY_PATH="/../build-host/cJSON/build" \
RUSTFLAGS='-L native=$(pwd)/../build-host/cJSON/build -l cjson -l cjson_utils' \
Notes:
- Use
-l cjson -l cjson_utilsto link the shared libraries, or link the static variants with-l static=cjson -l static=cjson_utilsand add the directory with-L native=.... - The project-level CMake already integrates
cJSONfor embedded builds; these steps let you reuse that same cJSON build artefact for running the host-side unit tests.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.