JSON Fixer
A robust Rust library for parsing and fixing malformed JSON. This library helps you handle common JSON formatting issues while maintaining the original data structure.
Features
- Fixes common JSON formatting issues:
- Unquoted object keys
- Missing commas in objects and arrays
- Trailing commas
- Single-quoted strings
- Simple syntax errors
- Closes unclosed brackets and braces
- Formatting options:
- Pretty printing with customizable indentation
- Space between keys and values
- Preserve original formatting
- Sort object keys alphabetically
- Detailed error reporting with line and column information
- Support for all JSON data types
- Proper handling of escape sequences
- Serde integration for type conversion (optional feature)
- No external dependencies (unless using serde features)
Installation
Add this to your Cargo.toml
:
[]
= "0.1.0" # Basic functionality
# Or with serde support:
= { = "0.1.0", = ["serde"] }
Usage
Basic JSON Fixing
use JsonFixer;
Formatting Options
use ;
// Pretty printing
let pretty_json = fix_pretty?;
// Result:
// {
// "name": "John",
// "age": 30,
// "hobbies": [
// "reading",
// "coding"
// ]
// }
// Add spaces between keys and values
let spaced_json = fix_with_space_between?;
// Result: { "name": "John", "age": 30, "hobbies": ["reading", "coding"] }
// Custom configuration
let mut config = default;
config.sort_keys = true;
config.indent_size = 2;
let custom_json = fix_with_config?;
Serde Integration
When enabled with the serde
feature, you can convert between JSON and Rust types:
use JsonFixer;
use ;
// Parse malformed JSON directly into a type
let input = r#"{ name: 'John', age: 30, hobbies: ['reading' 'coding'] }"#;
let person: Person = from_fixed?;
// Convert a type to properly formatted JSON
let json_string = to_json?;
// Parse valid JSON into a type
let valid_json = r#"{"name":"John","age":30,"hobbies":["reading","coding"]}"#;
let person: Person = from_str?;
Error Handling
The library provides detailed error information through the JsonFixerError
enum:
Examples
Fixing Missing Commas
// In arrays
let input = r#"[1 2 3 4]"#;
let fixed = fix?;
// Result: [1,2,3,4]
// In objects
let input = r#"{
name: "Hicham-dine"
age: 36
job: "programmer"
}"#;
let fixed = fix?;
// Result: {"name":"Hicham-dine","age":36,"job":"programmer"}
Sorting Object Keys
let input = r#"{
c: 3,
a: 1,
b: 2
}"#;
let mut config = default;
config.sort_keys = true;
let fixed = fix_with_config?;
// Result: {"a":1,"b":2,"c":3}
License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
TODOs and Future Improvements
- Full Support for JSON5 features
- Streaming input support
- Performance optimizations
Documentation
Full documentation is available at docs.rs.