Skip to main content

A library to parse and repair malformed JSON-like text.

Project description

JSONRescue

Overview

JSONRescue is a robust Python library designed to parse and repair malformed JSON-like text, specifically targeting common errors found in AI model responses that fail to return valid JSON. The library employs heuristics to identify, fix, and validate JSON structures against a provided schema, ensuring data consistency and correctness.

Features

  • Bracket Matching and Extraction: Uses advanced regex patterns to identify JSON-like structures within a text, even when nested.
  • Schema Validation: Ensures the parsed JSON adheres to a defined schema using a customizable Schema class.
  • Error Recovery: Attempts to fix common JSON errors, including:
    • Missing or unquoted keys.
    • Unquoted or improperly formatted string values.
    • Missing or extra brackets.
    • Escaping illegal characters.
  • Customizable Fixes: Implements modular methods for fixing specific JSON issues.

Installation

pip install jsonrescue

Usage

Example

from jsonrescue.custom_schema import Schema
from jsonrescue.parser import JSONRescue

# Define a schema for validation
schema = Schema(
    type='object',
    properties={
        'name': Schema(type='string'),
        'age': Schema(type='number'),
        'emails': Schema(type='array', items=Schema(type='string'))
    },
    required=['name', 'age']
)

parser = JSONRescue(schema)

malformed_json = """
{
    name: John Doe,
    age: 30,
    emails: ['john@example.com']
}
"""

parsed_data = parser.rescue(malformed_json)

if parsed_data:
    print("Valid JSON:", parsed_data)
else:
    print("Failed to parse JSON")

Examples of Errors Handled

  1. Missing Quotes Around Keys or Values:

    • Input: {name: John Doe, age: 22}
    • Output: {"name": "John Doe", "age": 22}
  2. Escaped Illegal Characters:

    • Input: { "name": "John \"Doe\"", "age": 30}
    • Output: { "name": "John \"Doe\"", "age": 30}
  3. Fixing Missing Brackets:

    • Input: {"name": "Jane"
    • Output: { "name": "Jane" }
  4. Handling Multiple Objects in Text:

    • Input: Here is {"name": "Dana", "age": 27}{"name": "Chris", "age": 35}
    • Output: {"name": "Dana", "age": 27} (First valid object parsed)
  5. Unquoted String Values:

    • Input: {"key": Value, "number": 123}
    • Output: {"key": "Value", "number": 123}

Key Components

Class: JSONRescue

Initialization

JSONRescue(schema: Schema)
  • schema: An instance of the Schema class defining the expected JSON structure.

Methods

  1. rescue(text: str) -> Any

    • Attempts to parse the input text as JSON.
    • Validates against the provided schema.
  2. extract_json_candidates(text: str) -> List[str]

    • Extracts potential JSON substrings from the input text using a bracket-matching regex.
  3. fix_json(json_str: str) -> str

    • Applies a sequence of fixes to a JSON string.
  4. fix_keys(json_str: str) -> str

    • Quotes unquoted object keys.
  5. fix_string_values(json_str: str) -> str

    • Quotes unquoted string values.
  6. escape_illegal_characters(json_str: str) -> str

    • Escapes problematic characters like newlines, tabs, and unescaped quotes.
  7. ensure_ending_brackets(json_str: str) -> str

    • Fixes mismatched or missing brackets.

Advanced Configuration

The library allows customization and extension by overriding its methods for specific JSON-repair scenarios. For example, you can add custom regex patterns or post-processing logic as needed.

Limitations

  • The parser assumes input text contains at least one valid JSON-like structure. Extremely malformed input may result in parsing failures.
  • It relies on heuristics to fix errors, which may not always produce the intended results.

Testing

The project includes a suite of unit tests to validate its functionality. To run the tests:

python -m unittest test.py

Example Test Cases

  • Proper JSON:

    input_text = '{"name": "John Doe", "age": 30, "emails": ["john@example.com"]}'
    expected = {"name": "John Doe", "age": 30, "emails": ["john@example.com"]}
    
  • Missing Required Field:

    input_text = '{"name": "Test", "emails": ["test@example.com"]}'
    assert parser_with_schema.rescue(input_text) is None
    
  • Incomplete Brackets:

    input_text = 'Start {"name": "Bob", "age": 35, "emails": ["bob@example.com"'
    expected = {"name": "Bob", "age": 35, "emails": ["bob@example.com"]}
    

Contributing

Contributions are welcome! Please fork the repository and submit a pull request with your changes.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jsonrescue-0.1.3.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

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

jsonrescue-0.1.3-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file jsonrescue-0.1.3.tar.gz.

File metadata

  • Download URL: jsonrescue-0.1.3.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.4

File hashes

Hashes for jsonrescue-0.1.3.tar.gz
Algorithm Hash digest
SHA256 fc87ce53be45e8c0b1eacbfdcb67fbd04e0aa5a2799915ff24ef6f0c3bc5dea5
MD5 447585453e9993f164677293dbaeede5
BLAKE2b-256 fab8a24fcba6bbe8f671b5c15c769748bac6f2eb22a56d79564ad2ca7ba463d2

See more details on using hashes here.

File details

Details for the file jsonrescue-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: jsonrescue-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.4

File hashes

Hashes for jsonrescue-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 ebe9b757679e01859667d66dbe0ad266ba56e5b92d6142ec57c6c645673a1f83
MD5 07c4ae9abbbf8f4c40b24fec66f077f4
BLAKE2b-256 d05ff96e7a9dafe17259ce6d5668034525b929bed260fcefd70dfb667f983ae4

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