A zero-dependency middleware to extract, clean, and heal JSON from messy LLM outputs.
Project description
pure-json
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
(Note: Currently in development. Will be available on PyPI soon.)
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: IfTrue, 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 aJSONHealingError.required_keys: If provided, validates that the parsed JSON is a dictionary containing all these keys. RaisesJSONValidationErrorif 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: IfTrue, 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 whenrequired_keysis passed toextract()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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
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 pure_json-0.1.0.tar.gz.
File metadata
- Download URL: pure_json-0.1.0.tar.gz
- Upload date:
- Size: 6.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
14524c57eaec1d5ec2eb37d17235265dda89dbd9cdcc4c4302190f7651cbe886
|
|
| MD5 |
69880cfa78caee42a2f2244c7a76541d
|
|
| BLAKE2b-256 |
1bbae1ecbee4bbec3ac76e31fca076b479621db5293e08a8c6e40dc539426bc5
|
File details
Details for the file pure_json-0.1.0-py3-none-any.whl.
File metadata
- Download URL: pure_json-0.1.0-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.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f73b32499e9c8a1c3bf88ea05e99a028a73d861b23193574d080e713671fd715
|
|
| MD5 |
18f84bd3dc96ab91db8a8a23d30a6222
|
|
| BLAKE2b-256 |
e52639babd3b5434dfdc21377040056e1d87936284024a55b73483cfeb226fe1
|