fast_json_repair
A high-performance JSON repair library for Python, powered by Rust. This is a drop-in replacement for json_repair with significant performance improvements.
๐ Attribution
This library is a Rust port of the excellent json_repair library created by Stefano Baccianella. The original Python implementation is a brilliant solution for fixing malformed JSON from Large Language Models (LLMs), and this port aims to bring the same functionality with improved performance.
All credit for the original concept, logic, and implementation goes to Stefano Baccianella. This Rust port maintains API compatibility with the original library while leveraging Rust's performance benefits.
If you find this library useful, please also consider starring the original json_repair repository.
Features
- ๐ฆ Available on PyPI:
pip install fast-json-repair - ๐ Rust Performance: Core repair logic implemented in Rust for maximum speed
- ๐ง Automatic Repair: Fixes common JSON errors automatically
- ๐ Python Compatible: Works with Python 3.11-3.14
- ๐ Drop-in Replacement: Compatible API with the original json_repair library
- โก Fast JSON Parsing: Uses orjson for JSON parsing operations
Compatibility with Original json_repair
This is a drop-in replacement for the original json_repair library with the same API:
โ Included:
repair_json()- Main repair function with object, logging, formatting, and validation optionsloads()- Convenience function for loading broken JSON directly to Python objectsjson.dumpsformatting arguments such asensure_ascii,indent,sort_keys, andseparators- Common repair capabilities: quotes, literals, commas, brackets, comments, wrappers, escape sequences, and Unicode
โ Not Included:
- File operations (
load(),from_file()) - Use Python's built-in file handling +repair_json() - CLI tool - Library-only implementation
- Streaming support - Not yet implemented
Key Differences:
- ๐ 30.5x geometric-mean speedup for malformed benchmark inputs
- ๐ข Unquoted numbers parsed as numbers (not strings)
- ๐ฆ Uses
orjsonfor high-performance JSON operations
Installation
Quick Install
pip install fast-json-repair
Build from Source
Click to expand build instructions
Prerequisites
- Python 3.11-3.14
- Rust toolchain (
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh) - uv (recommended) or pip
Quick Start with uv (Recommended)
# Clone the repository
git clone https://github.com/Rusty-Ports/fast_json_repair.git
cd fast_json_repair
# Run the automated setup script
./setup.sh
The setup script will:
- โ
Install
uvand Rust if needed - โ
Create a virtual environment (
.venv) - โ Install all dependencies
- โ Build the Rust extension
- โ Verify the installation
Manual Build Steps
# Clone the repository
git clone https://github.com/Rusty-Ports/fast_json_repair.git
cd fast_json_repair
# Option 1: Using uv (fast!)
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv sync
maturin develop --release
# Option 2: Using pip
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install maturin orjson
maturin develop --release
Usage
from fast_json_repair import repair_json, loads
# Fix broken JSON
broken = "{'name': 'John', 'age': 30}" # Single quotes
fixed = repair_json(broken)
print(fixed) # {"name":"John","age":30}
# Parse directly to Python object
data = loads("{'key': 'value'}")
print(data) # {'key': 'value'}
# Handle Unicode properly
text = "{'message': 'ไฝ ๅฅฝไธ็'}"
result = repair_json(text, ensure_ascii=False)
print(result) # {"message":"ไฝ ๅฅฝไธ็"}
# Format with indentation
formatted = repair_json("{'a': 1}", indent=2)
Inspect repairs
Pass logging=True to return the repaired object together with detailed repair
events. Diagnostics are collected only on this opt-in path.
data, repairs = repair_json("{name: 'Ada',}", logging=True)
for repair in repairs:
print(
repair["type"],
repair["line"],
repair["column"],
repair["context"],
)
Each event contains a stable type, a human-readable text description, nearby
source context, a zero-based UTF-8 byte position, and one-based line and
column values. Valid JSON returns an empty repair list.
What It Repairs
Automatically fixes common JSON formatting issues:
| Issue | Fix |
|---|---|
| Single quotes | โ Double quotes |
| Unquoted keys | โ Quoted keys |
| Python literals (True/False/None) | โ JSON (true/false/null) |
| Trailing commas | Removed |
| Missing commas | Added |
| Extra commas | Removed |
| Unclosed brackets/braces | Auto-closed |
| Invalid escape sequences | Fixed |
| Unicode characters | Preserved or escaped (configurable) |
| UTF-16 surrogate pairs | Combined into non-BMP characters |
| JavaScript comments | Removed |
| Markdown fences or surrounding text | JSON value extracted |
API Reference
repair_json(json_string, **kwargs)
Repairs invalid JSON and returns valid JSON string.
Parameters:
json_string(str): The potentially invalid JSON string to repairreturn_objects(bool): If True, return parsed Python object instead of JSON stringskip_json_loads(bool): If True, skip initial validation for better performancelogging(bool): If True, return the parsed object and detailed repair eventsstream_stable(bool): Accepted for API compatibilityensure_ascii(bool): If True, escape non-ASCII characters in outputindent(int): Number of spaces for indentation (None for compact output)**kwargs: Additional arguments forwarded tojson.dumps
Returns:
- str or object: Repaired JSON string or parsed Python object
- tuple: Parsed Python object and repair event list when
logging=True
loads(json_string, **kwargs)
Repairs and parses invalid JSON string to Python object.
Parameters:
json_string(str): The potentially invalid JSON string to repair and parse**kwargs: Additional arguments passed to repair_json
Returns:
- object: The parsed Python object
Performance
This Rust-based implementation provides significant performance improvements over the pure Python original.
Fast Path Optimization
The library automatically uses the fastest path when possible:
Fast Path (uses orjson and Rust ASCII escaping):
- Valid JSON input
indentis eitherNone(compact) or2
Fallback Path (uses stdlib json):
- Arbitrary-precision integers outside
orjson's 64-bit range - Custom
json.dumpsoptions or indentation values other thanNoneor2
Repair Path (uses Rust implementation):
- Any invalid JSON that needs repair
- Always respects
ensure_asciiandindentsettings
Benchmark Results
Version 0.2.2 was measured across 18 deterministic workloads, with 10 timed runs and 3 warmups per case. Validation occurs outside the timed region.
| Workload | fast_json_repair | json_repair | Speedup |
|---|---|---|---|
| Simple malformed object | 0.004 ms | 0.033 ms | 8.6x |
| Malformed array, 1000 numbers | 0.190 ms | 2.129 ms | 11.2x |
| Malformed object, 500 keys | 0.184 ms | 27.166 ms | 147.7x |
| Malformed array, 1000 objects | 1.814 ms | 665.509 ms | 366.9x |
| Malformed 10K string | 0.038 ms | 4.079 ms | 107.7x |
| Valid array, 1000 objects | 0.221 ms | 0.630 ms | 2.9x |
| Valid object, 500 keys | 0.151 ms | 0.389 ms | 2.6x |
Performance Advantages
- Malformed inputs: 30.5x geometric-mean speedup
- Valid inputs: 2.9x geometric-mean speedup
- All cases: 10.8x geometric-mean speedup
- Deep formatting: A 100K payload took 0.334 ms at depth 1 and 0.433 ms at depth 900
- Lower peak memory: The lexer streams over UTF-8 and the formatter writes into one output buffer
Run python benchmark.py to test performance on your system. See PERFORMANCE.md for detailed analysis.
AWS Deployment
Works seamlessly on AWS with pre-built wheels for all architectures:
- x86_64 - Standard EC2 instances (t2, t3, m5, c5, etc.)
- ARM64/aarch64 - Graviton instances (t4g, m6g, c6g, etc.)
# Install on any AWS instance - pip auto-selects the correct wheel
pip install fast-json-repair
For Lambda layers and cross-compilation, see DEPLOYMENT.md.
Development
Quick Reference
| Task | Command | VS Code Task |
|---|---|---|
| Setup | ./setup.sh |
- |
| Build (debug) | maturin develop |
๐ง Build: Development |
| Build (release) | maturin develop --release |
๐ Build: Development (Release) |
| Run tests | pytest tests/ -v |
๐งช Test: Python (All) |
| Run benchmarks | python benchmark.py |
โก Benchmark: Run Full Suite |
| Format code | cargo fmt && black . && isort . |
โจ Format: All (Rust + Python) |
| Lint Rust | cargo clippy |
๐ฆ Rust: Clippy |
| Lint Python | ruff check . |
๐ Python: Lint (Ruff) |
| Full check | maturin develop && pytest && python benchmark.py |
โ Full Check: Build + Test + Benchmark |
Quick Setup
# Automated setup (recommended)
./setup.sh
# Or manually with uv
uv venv && source .venv/bin/activate
uv sync
maturin develop
VS Code Integration
This project includes a complete VS Code workspace configuration:
Getting Started:
- Open the project folder in VS Code
- Install recommended extensions (you'll see a prompt)
- The Python interpreter will auto-detect
.venv - Press
Cmd+Shift+Pโ "Tasks: Run Task" to see all available commands
Available Tasks:
- ๐ง Build Tasks: Debug build, release build, wheels, cross-platform builds
- ๐งช Test Tasks: Run all tests, quick tests, coverage reports
- โก Benchmark Tasks: Full benchmarks, quick benchmarks, save results
- ๐ฆ Rust Tasks: Check, clippy, format, clean
- ๐ Python Tasks: Format (black), sort imports (isort), lint (ruff)
- ๐ข Workflows: Full check (build+test+benchmark), release prep, quality checks
Debugging:
- Press
F5to debug Python tests - Set breakpoints in Python code
- Use "Debug: Select and Start Debugging" for specific configs
Common Commands
See the Quick Reference table above for the most common tasks. Additional commands:
# Code quality
black . # Format Python code
isort . # Sort Python imports
ruff check . # Lint Python code
# Cross-platform builds (requires zig)
maturin build --release --target x86_64-unknown-linux-gnu --zig
maturin build --release --target aarch64-unknown-linux-gnu --zig
maturin build --release --target universal2-apple-darwin
Project Structure
fast_json_repair/
โโโ src/
โ โโโ lib.rs # Rust implementation (core repair logic)
โโโ python/
โ โโโ fast_json_repair/
โ โโโ __init__.py # Python API wrapper
โโโ tests/
โ โโโ test_all.py # Python test suite
โโโ benchmark.py # Performance benchmarks
โโโ pyproject.toml # Python package configuration
โโโ Cargo.toml # Rust package configuration
โโโ .vscode/ # VS Code workspace settings (local)
โโโ settings.json # Python/Rust interpreter & formatting
โโโ tasks.json # Build/test/benchmark tasks
โโโ launch.json # Debug configurations
โโโ extensions.json # Recommended extensions
Typical Workflow
- Make Changes - Edit Rust (
src/) or Python (python/) code - Rebuild -
maturin developor VS Code task๐ง Build: Development - Test -
pytest tests/ -vor VS Code task๐งช Test: Python (All) - Benchmark -
python benchmark.pyor VS Code taskโก Benchmark: Run Full Suite - Release -
maturin build --releasewhen ready to publish
License
MIT License (same as original json_repair)
Credits & Acknowledgments
Original Author
- Stefano Baccianella - Creator of the original json_repair library
- Original concept and algorithm design
- Python implementation that this library is based on
- Comprehensive test cases and edge case handling
This Rust Port
- Performance optimization through Rust implementation
- Maintains full API compatibility with the original
- Uses PyO3 for Python bindings
- Uses orjson for fast JSON parsing
Special Thanks
A huge thank you to Stefano Baccianella for creating json_repair and making it open source. This library wouldn't exist without the original brilliant implementation that has helped countless developers handle malformed JSON from LLMs.
If you appreciate this performance-focused port, please also show support for the original json_repair project that made it all possible.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fast_json_repair-0.2.3.tar.gz.
File metadata
- Download URL: fast_json_repair-0.2.3.tar.gz
- Upload date:
- Size: 68.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: maturin/1.14.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
bbd3266187da88b34d2a27eabe8a820d27f194f8a05ef86948a05781267a4643
|
|
| MD5 |
afd16f0a5be669e7164cae0e33dabd92
|
|
| BLAKE2b-256 |
d60372b0dcea7011fe8012c18f7112a6ed2208e2ce39cc64e9d31eeb65ace601
|
File details
Details for the file fast_json_repair-0.2.3-cp311-abi3-win_amd64.whl.
File metadata
- Download URL: fast_json_repair-0.2.3-cp311-abi3-win_amd64.whl
- Upload date:
- Size: 168.9 kB
- Tags: CPython 3.11+, Windows x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: maturin/1.14.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
84813bd235b6316dd6e675f5e331007fdbd26eb78f366477d1b19116167d1c90
|
|
| MD5 |
d879c64065b7e44407312fc770a48e53
|
|
| BLAKE2b-256 |
2e2219e74bb91548daca02013a8dcaf2b235872cdfc15fed4bebef25939c3f4f
|
File details
Details for the file fast_json_repair-0.2.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: fast_json_repair-0.2.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 270.0 kB
- Tags: CPython 3.11+, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: maturin/1.14.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
01f9ad995ee33890970235ac40d7e123d14ce0836df583f04303e921082db0a2
|
|
| MD5 |
67b30e6e78dd86a0e42d362da7e6f333
|
|
| BLAKE2b-256 |
9ab1ad5bd656020734afaf737149c99118d1da46792ef77ea89812700db54ded
|
File details
Details for the file fast_json_repair-0.2.3-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.
File metadata
- Download URL: fast_json_repair-0.2.3-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
- Upload date:
- Size: 260.4 kB
- Tags: CPython 3.11+, manylinux: glibc 2.17+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: maturin/1.14.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fe143a0dfc492edb0521a52a003ccfe9352a05ac49eaf3537f2cbb4830061cf8
|
|
| MD5 |
2c18b2a1f11ec8ba1e261597340244d0
|
|
| BLAKE2b-256 |
207d819b4de7ab7884896e5c4cbc14a4bb2d47de5ccaaedb68c486ac644e0373
|
File details
Details for the file fast_json_repair-0.2.3-cp311-abi3-macosx_11_0_arm64.whl.
File metadata
- Download URL: fast_json_repair-0.2.3-cp311-abi3-macosx_11_0_arm64.whl
- Upload date:
- Size: 238.9 kB
- Tags: CPython 3.11+, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: maturin/1.14.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
46b94a5f45c5cf32fc0b31ac284a16a8994efa937cc7cdcfe1ad1eb22684002f
|
|
| MD5 |
0a45b1cf7f7c5af684df11f4b72e5645
|
|
| BLAKE2b-256 |
db825b19ce47af7f4607299ad0fa26104b12464365bfcde7ac087f0dcef95c1b
|
File details
Details for the file fast_json_repair-0.2.3-cp311-abi3-macosx_10_12_x86_64.whl.
File metadata
- Download URL: fast_json_repair-0.2.3-cp311-abi3-macosx_10_12_x86_64.whl
- Upload date:
- Size: 250.5 kB
- Tags: CPython 3.11+, macOS 10.12+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: maturin/1.14.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5bf4360501109abad0b981672fa1ce922aff18c8f4dd9e3a702e1d3c7f8e6b5b
|
|
| MD5 |
e21a689d645bb597d8e618090ff4f891
|
|
| BLAKE2b-256 |
3fccfb50ab9574dffeef7aec081dfc8b57e6bc2e9b6a952eac094d73758ca8be
|