jsonrepair_rs/lib.rs
1//! # jsonrepair-rs
2//!
3//! Repair broken JSON — fix quotes, commas, comments, trailing content,
4//! and 30+ other issues commonly found in LLM outputs.
5//!
6//! Port of the JavaScript [jsonrepair](https://github.com/josdejong/jsonrepair) library.
7//!
8//! ## Usage
9//!
10//! ```
11//! use jsonrepair_rs::jsonrepair;
12//!
13//! // Fix single quotes (whitespace preserved)
14//! let result = jsonrepair("{'name': 'John'}").unwrap();
15//! assert_eq!(result, r#"{"name": "John"}"#);
16//!
17//! // Fix trailing commas
18//! let result = jsonrepair(r#"{"a": 1, "b": 2,}"#).unwrap();
19//! assert_eq!(result, r#"{"a": 1, "b": 2}"#);
20//!
21//! // Convert Python keywords
22//! let result = jsonrepair(r#"{"flag": True, "value": None}"#).unwrap();
23//! assert_eq!(result, r#"{"flag": true, "value": null}"#);
24//! ```
25
26mod chars;
27mod error;
28mod parser;
29
30pub use error::{JsonRepairError, JsonRepairErrorKind};
31
32/// Repair a broken JSON string, returning valid JSON.
33///
34/// Handles 30+ categories of issues including:
35/// - Single/curly quotes → double quotes
36/// - Trailing/missing commas
37/// - Comments (`//`, `/* */`, `#`)
38/// - Python keywords (`True`, `False`, `None`)
39/// - JavaScript keywords (`undefined`, `NaN`, `Infinity`)
40/// - Markdown code fences
41/// - JSONP wrappers
42/// - Unquoted keys and strings
43/// - Truncated JSON (auto-closes brackets)
44/// - String concatenation (`"a" + "b"`)
45/// - Invalid escape sequences
46/// - Leading zeros, truncated numbers
47/// - MongoDB constructors (`ObjectId(...)`)
48/// - NDJSON (newline-delimited JSON)
49/// - Ellipsis operators (`...`)
50///
51/// Returns `Err(JsonRepairError)` if the input cannot be repaired.
52pub fn jsonrepair(input: &str) -> Result<String, JsonRepairError> {
53 let repairer = parser::JsonRepairer::new(input);
54 repairer.repair()
55}