Skip to main content

fast_json_repair

PyPI version Python 3.11-3.14 License: MIT

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 options
  • loads() - Convenience function for loading broken JSON directly to Python objects
  • json.dumps formatting arguments such as ensure_ascii, indent, sort_keys, and separators
  • 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 orjson for 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/dvideby0/fast_json_repair.git
cd fast_json_repair

# Run the automated setup script
./setup.sh

The setup script will:

  • โœ… Install uv and 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/dvideby0/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)

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 repair
  • return_objects (bool): If True, return parsed Python object instead of JSON string
  • skip_json_loads (bool): If True, skip initial validation for better performance
  • logging (bool): If True, return the parsed object and a repair log
  • stream_stable (bool): Accepted for API compatibility
  • ensure_ascii (bool): If True, escape non-ASCII characters in output
  • indent (int): Number of spaces for indentation (None for compact output)
  • **kwargs: Additional arguments forwarded to json.dumps

Returns:

  • str or object: Repaired JSON string or parsed Python object

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
  • indent is either None (compact) or 2

Fallback Path (uses stdlib json):

  • Arbitrary-precision integers outside orjson's 64-bit range
  • Custom json.dumps options or indentation values other than None or 2

Repair Path (uses Rust implementation):

  • Any invalid JSON that needs repair
  • Always respects ensure_ascii and indent settings

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:

  1. Open the project folder in VS Code
  2. Install recommended extensions (you'll see a prompt)
  3. The Python interpreter will auto-detect .venv
  4. 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 F5 to 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

  1. Make Changes - Edit Rust (src/) or Python (python/) code
  2. Rebuild - maturin develop or VS Code task ๐Ÿ”ง Build: Development
  3. Test - pytest tests/ -v or VS Code task ๐Ÿงช Test: Python (All)
  4. Benchmark - python benchmark.py or VS Code task โšก Benchmark: Run Full Suite
  5. Release - maturin build --release when 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

fast_json_repair-0.2.2.tar.gz (64.4 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

fast_json_repair-0.2.2-cp311-abi3-win_amd64.whl (149.4 kB view details)

Uploaded CPython 3.11+Windows x86-64

fast_json_repair-0.2.2-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (253.2 kB view details)

Uploaded CPython 3.11+manylinux: glibc 2.17+ x86-64

fast_json_repair-0.2.2-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (244.3 kB view details)

Uploaded CPython 3.11+manylinux: glibc 2.17+ ARM64

fast_json_repair-0.2.2-cp311-abi3-macosx_11_0_arm64.whl (223.0 kB view details)

Uploaded CPython 3.11+macOS 11.0+ ARM64

fast_json_repair-0.2.2-cp311-abi3-macosx_10_12_x86_64.whl (232.7 kB view details)

Uploaded CPython 3.11+macOS 10.12+ x86-64

File details

Details for the file fast_json_repair-0.2.2.tar.gz.

File metadata

  • Download URL: fast_json_repair-0.2.2.tar.gz
  • Upload date:
  • Size: 64.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: maturin/1.14.1

File hashes

Hashes for fast_json_repair-0.2.2.tar.gz
Algorithm Hash digest
SHA256 465d3469f37ec9cd105b9ad5cdaaa8940810a5bd1cd53fc104d7110e4404d2d1
MD5 8fcc06cab351d06a9ac2c57fd16d9b6e
BLAKE2b-256 896b58f36d1a8ffd05324eca7db9f7d7dc1f3c555926d67a93be725b0da83a08

See more details on using hashes here.

File details

Details for the file fast_json_repair-0.2.2-cp311-abi3-win_amd64.whl.

File metadata

File hashes

Hashes for fast_json_repair-0.2.2-cp311-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 805818530fdd25b0f9a5e6b2542104f72fe219b4b7bb37d71867549351039db9
MD5 b34860e099d0ec156aa0fbf5cebb9d87
BLAKE2b-256 6ccdc899fb44d141ba52e24d0a0b969ba30f6fcfa6837ba16f3b9e5d7023bb05

See more details on using hashes here.

File details

Details for the file fast_json_repair-0.2.2-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for fast_json_repair-0.2.2-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 554f425b2af9fc77caa688c12aacb9b11f37501727d3cde20c852af977b8009f
MD5 b8b3eb18e9cde6694d83496e61e670ec
BLAKE2b-256 eb9b133370bf20cd5001789beabb889054ad366ea638a1a2d6ed1962bbb63dbe

See more details on using hashes here.

File details

Details for the file fast_json_repair-0.2.2-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for fast_json_repair-0.2.2-cp311-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 777432541115a94bc82d12656ac7615b863c2b3b6b945f4727601ec4794ac70f
MD5 9c61e588accab36a5754a115e559db42
BLAKE2b-256 cd830ef86996652766cfff1ccd2212aecc1ef2677c15d1f73a1360870082d8ac

See more details on using hashes here.

File details

Details for the file fast_json_repair-0.2.2-cp311-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for fast_json_repair-0.2.2-cp311-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 eed79d0aa4bf6e91be073594304e5a4334ecbeafaf287a6e552a8724a08e346e
MD5 4a2c67150781474c2b2b3daf023fc243
BLAKE2b-256 2abb1cf4c1b4140570cadef1f96c026ef5dce8c40124817f4a8273c978e0fbf5

See more details on using hashes here.

File details

Details for the file fast_json_repair-0.2.2-cp311-abi3-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for fast_json_repair-0.2.2-cp311-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 b91d79e9fc822e2fbcab0ee23dbda2422547636b544b848e1d098d9181465905
MD5 cb43f66fcaef90f18d7369d174c36c13
BLAKE2b-256 20f0a0d1f2a40b2b2dd3af86cbbae2368a459c4354eee49066ec52717c983e2f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page