Skip to main content

llm-json-heal

PyPI Python CI License: MIT

Recover JSON from messy LLM output. Zero dependencies, standard library only.

Language models asked for JSON routinely return something json.loads rejects:

  • the payload wrapped in prose or a Markdown code fence
  • trailing commas, missing commas, missing colons, unquoted keys
  • literal newlines and tabs inside strings, stray control characters
  • invalid escapes from regexes and Windows paths ("\d+", "C:\Users")
  • unescaped double quotes inside a string value
  • a reply cut off mid-object by a token limit
  • Python-style dicts ({'a': True, 'b': None})

llm-json-heal finds the payload, repairs it, and hands you a normal Python object.

Install

pip install llm-json-heal

Usage

from llm_json_heal import loads

reply = r'''Sure! Here is my analysis:
```json
{
  "verdict": "VULNERABLE",
  "confidence": 0.9,
  "reasoning": "User input reaches $wpdb->query()
without prepare()",
  "patterns": ["\d+", "C:\Users\admin"],
}
```
Let me know if you need more detail.'''

loads(reply)
# {'verdict': 'VULNERABLE', 'confidence': 0.9,
#  'reasoning': 'User input reaches $wpdb->query()\nwithout prepare()',
#  'patterns': ['\\d+', 'C:\\Users\\admin']}

Truncated replies are closed instead of rejected:

loads('{"verdict": "VULNERABLE", "reasoning": "The input flows into')
# {'verdict': 'VULNERABLE', 'reasoning': 'The input flows into'}

When nothing can be recovered, loads raises JSONHealError (a ValueError), or returns a default you supply:

from llm_json_heal import loads, JSONHealError

loads("I could not analyse this file.", default={})   # -> {}

try:
    loads("no json here")
except JSONHealError as exc:
    print(exc, exc.text)

How it works

loads(text) runs these steps, stopping as soon as one yields valid JSON:

  1. Locate the payload: the whole reply, then fenced code blocks, then the first balanced top-level object or array in the prose. Braces inside strings are ignored, and an inner object is never returned in place of the broken outer object that contains it.
  2. Heal: remove control characters, escape literal newlines and tabs inside strings, drop trailing commas, double backslashes that don't start a valid JSON escape.
  3. Repair: read the position of each json.JSONDecodeError and apply one targeted fix (insert a missing , or :, quote a bare key, escape a stray quote, drop trailing data). Repeat up to max_repairs times.
  4. Close a truncated document: terminate an open string, resolve a dangling , or :, drop an incomplete last member, append the missing ] and }.
  5. Fall back to ast.literal_eval for Python-literal syntax.

Lower-level API

Each step is also exposed on its own:

Function Purpose
extract_json(text) Return the sanitized payload string, or None
find_complete_json(text) Return the balanced object or array at the start of text
sanitize_json_string(s) Control characters + heal + escape fixing
heal_json_string(s) Escape literal whitespace in strings, drop trailing commas
strip_control_characters(s) Remove ASCII control characters except \t\n\r
repair_json(s, error) One fix for a given JSONDecodeError
close_truncated_json(s) Close a cut-off document, or None

Normalizing field values

Models are also inconsistent about values. A few helpers cover the common cases:

from llm_json_heal import to_percentage, clamp, pick, ensure_list

to_percentage("0.85")      # 85
to_percentage("92%")       # 92
clamp("7.53/10", 0, 10, ndigits=1)            # 7.5
pick("High risk", ["CRITICAL", "HIGH", "MEDIUM", "LOW"])  # 'HIGH'
ensure_list("xss, sqli")   # ['xss', 'sqli']

Limitations

  • An unescaped quote inside a string is ambiguous. The repair heuristics handle common cases such as "he said "hi" ok", but cannot always recover the intended text.
  • Truncation recovery keeps every complete member and drops the incomplete one. It never invents values beyond closing an open string or setting a dangling key to null.
  • The input is assumed to hold one main payload. If a reply contains several independent JSON objects, the first one that parses is returned.

Origin

Extracted from the LLM verification stage of the ARKA WordPress plugin vulnerability scanner, where it parsed findings from local (Ollama) and hosted models.

License

MIT

Metadata

Release files for llm-json-heal 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llm-json-heal 0.1.0
File Size Uploaded Provenance Actions
llm_json_heal-0.1.0.tar.gz 12.8 kB Without provenance Details for llm_json_heal-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for llm-json-heal 0.1.0
File Interpreter ABI Platform Actions
llm_json_heal-0.1.0-py3-none-any.whl Python 3 none any Details for llm_json_heal-0.1.0-py3-none-any.whl

Total release size: 25.3 kB

Release files / llm_json_heal-0.1.0.tar.gz

Download URL llm_json_heal-0.1.0.tar.gz
Size 12.8 kB
Tags Source
SHA-256 checksum
How to use checksums
37e849aee11699c769d9dd8b0324fff3a961727c8e76154f860500de0cf2bfb7
BLAKE2b-256 checksum
How to use checksums
b7de915bf8918fa0648ed0f7e95eb0787c37d2dc6a2bb9edffcd64b6cedf0fa4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

Release files / llm_json_heal-0.1.0-py3-none-any.whl

Download URL llm_json_heal-0.1.0-py3-none-any.whl
Size 12.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a9d36bd991a0b7665c105d0aa1294a77d54ab4e2033ccfd7b73c1ba16fd93d39
BLAKE2b-256 checksum
How to use checksums
c000b8c269109c54ebf3a64591609418337cd9e8e9129950443dc7d2988d22c1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

Security for llm-json-heal 0.1.0

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page