Skip to main content

A zero-dependency middleware to extract, clean, and heal JSON from messy LLM outputs.

Project description

pure-json

Python 3.8+ License: MIT PyPI - Version

pure-json is a lightweight, zero-dependency Python library designed to extract, clean, and parse JSON from messy Large Language Model (LLM) string outputs.

LLMs frequently return JSON surrounded by conversational fluff (e.g., "Here is your JSON:") or Markdown formatting (```json ... ```). Furthermore, they often make syntax errors like trailing commas, unquoted keys, or use single quotes (outputting Python dicts instead of valid JSON). pure-json acts as a middleware to automatically heal these issues so your pipelines don't break.

Features

  • Fluff Stripping: Automatically detects the outermost JSON bounds and ignores conversational text and Markdown blocks.
  • Auto-Healing:
    • Removes trailing commas.
    • Converts unquoted Python types (True, False, None) to JSON literals (true, false, null).
    • Swaps single quotes (') for double quotes (").
    • Quotes unquoted keys (e.g., {key: "value"} -> {"key": "value"}).
  • Schema Validation: Pass a list of required keys to ensure the LLM followed your schema, raising a specific error if keys are missing.
  • Multiple Blocks: Extract every distinct JSON object from a single string using extract_all().
  • Zero Dependencies: Uses only the Python standard library.
  • Strict Mode: Optional mode to fail fast on invalid JSON if you prefer to trigger an LLM retry instead of auto-healing.

Installation

pip install pure-json

Quick Start

from pure_json import extract

messy_output = """
Sure! Here is the output you requested:
```json
{
  'status': "success",
  error_code: None,
  "data": [1, 2, 3,]
}
```
Let me know if you need anything else!
"""

# Extract and auto-heal the JSON
parsed_data = extract(messy_output)
print(parsed_data)
# Output: {'status': 'success', 'error_code': None, 'data': [1, 2, 3]}

API Reference

extract(text: str, strict: bool = False, required_keys: list[str] = None) -> Any

Arguments:

  • text: The raw string containing the JSON you want to extract.
  • strict: If True, disables the auto-healer. The library will still strip conversational fluff and Markdown, but if the extracted string is not valid JSON, it will immediately raise a JSONHealingError.
  • required_keys: If provided, validates that the parsed JSON is a dictionary containing all these keys. Raises JSONValidationError if any are missing.

Returns:

  • The parsed JSON object (dict, list, etc.).

extract_all(text: str, strict: bool = False) -> list[Any]

Arguments:

  • text: The raw string containing multiple JSON blocks you want to extract.
  • strict: If True, disables the auto-healer for each block.

Returns:

  • A list of all parsed JSON objects found in the string.

Exceptions

  • JSONExtractionError: Raised when the library cannot locate valid JSON boundaries (no {...} or [...] found).
  • JSONHealingError: Raised when the library cannot parse the extracted text into valid JSON (either because strict mode is on, or because the auto-healer failed to fix the syntax errors).
  • JSONValidationError: Raised when required_keys is passed to extract() and the parsed JSON is missing one or more of those keys.

Handling Errors

It's recommended to catch these custom exceptions in your pipeline and use them to trigger a retry to the LLM.

from pure_json import extract, JSONExtractionError, JSONHealingError, JSONValidationError

def process_llm_output(output):
    try:
        # Require 'status' and 'data' keys to be present
        data = extract(output, required_keys=["status", "data"])
        return data
    except JSONExtractionError:
        print("LLM didn't return any JSON object.")
        # Trigger LLM retry...
    except JSONHealingError as e:
        print(f"LLM returned hopelessly invalid JSON: {e}")
        # Trigger LLM retry...
    except JSONValidationError as e:
        print(f"LLM hallucinated the schema: {e}")
        # Trigger LLM retry...

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

pure_json-0.1.1.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

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

pure_json-0.1.1-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file pure_json-0.1.1.tar.gz.

File metadata

  • Download URL: pure_json-0.1.1.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for pure_json-0.1.1.tar.gz
Algorithm Hash digest
SHA256 06be7b3685f7571077c4ce2b8f1fbad9ea1c89acc8eeb32d59a7311f0180dda7
MD5 0b27305bbeebf5192a5fe4ab7df00b98
BLAKE2b-256 4a5645a658bedc91cc1092a60c6b8c798537e6905f07897192f5581cd065f291

See more details on using hashes here.

File details

Details for the file pure_json-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: pure_json-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 6.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.20

File hashes

Hashes for pure_json-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9f40ba39b68481b75a8b15cb056f5cb199789c51eb7ba16b3abb24a0a08f1179
MD5 161319ed5979200936dd05117eba93c4
BLAKE2b-256 2ff31ec8b25c4f305d753920669831271b974b378ffb8ec99f010f637789978d

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