UNPKG

json-repair-js

Version:

JavaScript library to repair broken/invalid JSON strings, especially from LLM outputs

73 lines (55 loc) 1.81 kB
# json-repair-js A JavaScript library that repairs JSON strings generated by LLMs or corrupted ones. ## Features - Automatically detects and parses JSON from LLM outputs - Fixes missing quotation marks - Fixes missing commas - Preserves Unicode characters - Finds JSONs in Markdown/text ## Installation ```bash npm install json-repair-js ``` ## Usage ```javascript 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 }); ``` ## Features and Fixes 1. Fixing missing quotation marks: ```javascript '{ name: John }' -> '{ "name": "John" }' ``` 2. Fixing missing commas: ```javascript '["a" "b" "c"]' -> '["a", "b", "c"]' ``` 3. Cleaning LLM outputs: ```javascript 'Here is the JSON: ```json { "key": "value" }```' -> '{ "key": "value" }' ``` 4. Preserving Unicode characters: ```javascript repairJson('{ test: "Türkçe" }', { ensureAscii: false }) // Output: { "test": "Türkçe" } ``` ## License MIT