A JavaScript library that repairs JSON strings generated by LLMs or corrupted ones.
- Automatically detects and parses JSON from LLM outputs
- Fixes missing quotation marks
- Fixes missing commas
- Preserves Unicode characters
- Finds JSONs in Markdown/text
npm install json-repair-js
const { repairJson, loads } = require('json-repair-js');
// Basic usage
const brokenJson = '{ name: John, age: 30 }';
const result = loads(brokenJson);
console.log(result); // { name: "John", age: 30 }
// Parsing JSON from an LLM output
const llmOutput = `I understand, here's a suitable JSON for you: \`\`\`json
{
"title": "Sample Title",
"items": ["item1" "item2" "item3"]
}`;
const parsed = loads(llmOutput);
console.log(parsed); // { title: "Sample Title", items: ["item1", "item2", "item3"] }
// Using repairJson for more detailed checks
const result2 = repairJson(brokenJson, {
returnObjects: false, // true: returns a JavaScript object, false: returns a JSON string
skipJsonParse: false, // true: skips JSON.parse check
logging: false, // true: returns repair logs as well
ensureAscii: true // false: preserves Unicode characters
});
- Fixing missing quotation marks:
'{ name: John }' -> '{ "name": "John" }'
- Fixing missing commas:
'["a" "b" "c"]' -> '["a", "b", "c"]'
- Cleaning LLM outputs:
'Here is the JSON: ```json { "key": "value" }```' -> '{ "key": "value" }'
- Preserving Unicode characters:
repairJson('{ test: "Türkçe" }', { ensureAscii: false })
// Output: { "test": "Türkçe" }
MIT