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
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...
Metadata
Release files for pure-json 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| pure_json-0.1.1.tar.gz | 6.2 kB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| pure_json-0.1.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 12.5 kB
Release files / pure_json-0.1.1.tar.gz
| Download URL | pure_json-0.1.1.tar.gz |
|---|---|
| Size | 6.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
06be7b3685f7571077c4ce2b8f1fbad9ea1c89acc8eeb32d59a7311f0180dda7
|
|
BLAKE2b-256 checksum How to use checksums |
4a5645a658bedc91cc1092a60c6b8c798537e6905f07897192f5581cd065f291
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.20
|
Release files / pure_json-0.1.1-py3-none-any.whl
| Download URL | pure_json-0.1.1-py3-none-any.whl |
|---|---|
| Size | 6.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9f40ba39b68481b75a8b15cb056f5cb199789c51eb7ba16b3abb24a0a08f1179
|
|
BLAKE2b-256 checksum How to use checksums |
2ff31ec8b25c4f305d753920669831271b974b378ffb8ec99f010f637789978d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.10.20
|
Security for pure-json 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.