# serde-json-diagnostics
A serde_json extension for better deserialization error diagnostics with
accurate JSON path tracking.
## Overview
This crate provides drop-in replacements for `serde_json::from_str`,
`serde_json::from_slice`, and `serde_json::from_reader` that return enhanced
errors with JSON path information. The path tracking helps you quickly identify
where in your JSON structure a deserialization error occurred.
**Current Status**: Phase 1 complete - API is functional and ready for use. Path
tracking implementation is pending and will be added in a future update.
## Installation
Add this to your `Cargo.toml`:
```toml
[dependencies]
serde_json_diagnostics = "0.1.0"
```
## Usage
Replace your `serde_json` deserialization calls with the equivalents from this
crate:
```rust
use serde::Deserialize;
use serde_json_diagnostics::from_str;
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
}
fn main() -> Result<(), serde_json_diagnostics::ErrorDiagnostic> {
let json = r#"{"name": "Alice", "age": 30}"#;
let user: User = from_str(json)?;
println!("User: {} is {} years old", user.name, user.age);
Ok(())
}
```
### API Functions
The crate provides three functions with the same signatures as `serde_json`:
- `from_str<'a, T>(s: &'a str) -> Result<T>` - Deserialize from a JSON string
- `from_slice<'a, T>(bytes: &'a [u8]) -> Result<T>` - Deserialize from a byte
slice
- `from_reader<R, T>(reader: R) -> Result<T>` - Deserialize from an IO reader
All functions return `Result<T, ErrorDiagnostic>` instead of
`Result<T, serde_json::Error>`.
## Example: Error Handling
```rust
use serde::Deserialize;
use serde_json_diagnostics::from_str;
#[derive(Deserialize)]
struct Config {
debug: bool,
port: u16,
}
let json = r#"{"debug": true, "port": "invalid"}"#;
match from_str::<Config>(json) {
Ok(config) => println!("Loaded config: {:?}", config),
Err(e) => eprintln!("Failed to parse JSON: {}", e),
}
```
## Features
- Drop-in replacement for `serde_json::from_str`, `from_slice`, and
`from_reader`
- Same API signatures as serde_json (only error type changes)
- Enhanced error type (`ErrorDiagnostic`) that wraps `serde_json::Error`
- Path tracking (WIP)
## Why This Crate?
The standard `serde_path_to_error` crate has
[known issues](https://github.com/dtolnay/path-to-error/issues/1) with path
tracking for certain enum representations (internally tagged, adjacently tagged,
and untagged enums). This crate aims to provide more reliable path tracking
using breadcrumb-style navigation, while maintaining the same ergonomic API as
`serde_json`.
Credits to [@BrokenStandards](https://github.com/BrokenStandards).
## License
MIT License.
## Acknowledgments
- [serde](https://github.com/serde-rs/serde) - Serialization framework for Rust
- [serde_json](https://github.com/serde-rs/json) - JSON support for serde
- [serde_path_to_error](https://github.com/dtolnay/path-to-error) - Find out
path at which a deserialization error occurred