json-repair-llm
v0.1.0
Published
Repair broken JSON from LLM outputs. Fix trailing commas, single quotes, unquoted keys, truncated objects, and more.
Maintainers
Readme
json-repair-llm
Repair broken JSON from LLM outputs. Fix trailing commas, single quotes, unquoted keys, truncated objects, missing brackets, and Python literals — all without dependencies.
The Problem
LLMs frequently return invalid JSON: trailing commas, single quotes instead of double, True/False/None instead of true/false/null, missing closing brackets from truncated output, or JSON wrapped in markdown code blocks. JSON.parse() throws. This library fixes it.
Install
npm install json-repair-llmQuick Start
const { repair, extract } = require('json-repair-llm');
// Fix broken JSON
repair("{'name': 'Alice', 'age': 30,}")
// → '{"name": "Alice", "age": 30}'
// Extract JSON from LLM markdown output
extract("Here's the data:\n```json\n{\"x\": 1}\n```\nDone!")
// → { x: 1 }API
repair(str)
Returns a repaired JSON string. Fixes:
- Trailing commas:
{a: 1,}→{a: 1} - Single quotes:
{'a': 'b'}→{"a": "b"} - Unquoted keys:
{name: "Alice"}→{"name": "Alice"} - Python booleans:
True/False/None→true/false/null - Missing closing brackets from truncation
- Escaped single quotes inside strings
- Comments (// and /* */)
extract(text)
Extracts and parses JSON from messy LLM output. Returns parsed object/array or null.
Handles: bare JSON, ```json code blocks, JSON embedded in text.
safeParseJSON(str)
Like JSON.parse() but tries repair first. Returns { data, error }.
License
MIT
