Fix Broken JSON and LLM Output – json-repair-js

Category: Javascript | November 11, 2026
Authorahgsql
Last UpdateNovember 11, 2026
LicenseMIT
Tags
Views0 views
Fix Broken JSON and LLM Output – json-repair-js

json-repair-js is a JavaScript utility for repairing malformed JSON found in LLM responses and other text.

It recovers JSON objects and arrays and returns a parsed JavaScript value or a formatted JSON string.

Features

  • Repairs missing quotes, commas, and closing brackets.
  • Extracts JSON from Markdown code fences and surrounding prose.
  • Handles single quotes, typographic quotes, and escape sequences.
  • Skips line and block comments.
  • Converts Python literals and tuples into JSON-compatible values.
  • Retains complete values in unfinished JSON streams.
  • Includes optional repair logs and TypeScript declarations.

How To Use It

Installation

Install the npm package for basic JSON repair:

npm install json-repair-js

For comment handling, Python values, streaming support, and TypeScript declarations, install the newer GitHub source:

npm install github:ahgsql/json-repair-js#fabd0f4c3214c86847c2a05fc45dd6bddbe2a65a

The package uses CommonJS. Bundle it for use in browser code.

Basic Usage

const { loads, repairJson } = require('json-repair-js');
const broken = '{ name: John, age: 30 }';
const data = loads(broken);
console.log(data); // { name: 'John', age: 30 }
const json = repairJson(broken);
console.log(json);

Extract JSON From an LLM Response

Pass the whole response to loads() when an object or array is embedded in explanatory text.

const { loads } = require('json-repair-js');
const response = `Here is the result:
\`\`\`json
{ title: "Release Notes", tags: ["JavaScript" "AI"] }
\`\`\``;
const result = loads(response);
console.log(result);
// { title: 'Release Notes', tags: ['JavaScript', 'AI'] }

Handle Python Values and Comments

const { loads } = require('json-repair-js');
const response = `{
  'ready': True, // generated by a Python tool
  'fallback': None,
  'point': (12, 34)
}`;
console.log(loads(response));
// { ready: true, fallback: null, point: [12, 34] }

Read Partial JSON During Streaming

Pass accumulated response text with streamStable: true to omit incomplete terminal values.

const { loads } = require('json-repair-js');
console.log(loads('{"a": 1, "b": 12', { streamStable: true }));
// { a: 1 }
console.log(loads('{"a": 1, "b": 123}', { streamStable: true }));
// { a: 1, b: 123 }
console.log(loads('{"a": 1, "text": "Hel', { streamStable: true }));
// { a: 1, text: 'Hel' }

Get Repair Logs

Set logging: true to inspect recorded repairs.

const { repairJson } = require('json-repair-js');
const [value, logs] = repairJson(
  '{ "a" 1 }',
  { logging: true }
);
console.log(value); // { a: 1 }
console.log(logs[0]);
// { text: 'Missing colon after key, adding it', context: '{ "a" 1 }' }

Read JSON From a File

In Node.js, fromFile() reads a UTF-8 file synchronously and returns the recovered value.

const { fromFile } = require('json-repair-js');
const data = fromFile('./llm-response.txt');
console.log(data);

Use the TypeScript Definitions

import { loads, repairJson } from 'json-repair-js';
const record = loads<{ name: string }>('{ name: Ada }');
const json: string = repairJson('{ name: Ada }');
const [value, logs] = repairJson('{ name: Ada }', {
  logging: true
});

Public API

FunctionDescription
repairJson(jsonStr = "", options = {})Returns a formatted JSON string by default. Returns a parsed JavaScript value with returnObjects: true, or [value, logs] with logging: true.
loads(jsonStr, options = {})Repairs and parses a JSON string into a JavaScript value. With logging: true, returns [value, logs].
fromFile(filename, options = {})Reads a UTF-8 file synchronously through Node.js and processes it with loads(). Supports the same logging behavior.

Configuration Options

OptionDescription
returnObjectsBoolean, default false. Makes repairJson() return a parsed value. loads() and fromFile() always use parsed values.
skipJsonParseBoolean, default false. Skips the initial native JSON.parse() attempt and uses the repair parser directly.
loggingBoolean, default false. Returns [value, logs] for repaired JSON. The GitHub-source version also uses this format for valid JSON. Each recorded repair includes text and context.
ensureAsciiBoolean, default true. When repairing Unicode text, the default can introduce literal \uXXXX sequences into the parsed string values. Set false to preserve the characters.
streamStableBoolean, default false. Omits incomplete terminal numbers, literals, and object entries while preserving partial strings.

TypeScript Types

ExportDescription
JsonValueRecursive JSON value type: string, number, boolean, null, arrays, or objects.
RepairLogEntryLog object with text and context string properties.
RepairOptionsOption type for repairJson(), including all five configuration flags.
LoadsOptionsOption type for loads() and fromFile(), excluding returnObjects.

Alternatives and Related Resources

FAQs

Does json-repair-js extract every JSON block from one response?

It parses the first object or array found in the text. Process multiple payloads separately.

Can it parse JSON primitives?

Valid JSON primitives such as true and 42 are parsed directly. For malformed input, the repair parser searches for an object or array.

Does json-repair-js validate JSON against a schema?

Use a JSON Schema validator to check required fields and types in the recovered value.

You Might Be Interested In:


Leave a Reply