JSON Repair
Free online JSON Repair tool. Auto-detects and fixes trailing commas, single quotes, unquoted keys, unclosed brackets, comments and Markdown wrappers. Built for AI output cleanup and truncated JSON recovery. Entirely local in your browser.
Related
What is JSON Repair?
JSON Repair is the process of taking a non-standard JSON text that cannot be consumed by a strict JSON parser due to syntax errors and automatically restoring it into a valid JSON string that conforms to RFC 8259. Unlike JSON Formatter (Beautify), JSON Repair does not address formatting differences but structural errors: trailing commas, single quotes, missing quotes, unclosed brackets, Markdown wrappers, comments — all of which cause JSON.parse() to throw a SyntaxError, yet are extremely common in real-world development.
The sources of "non-standard" JSON in real engineering projects are highly concentrated: ① When copying from LLMs like ChatGPT / Claude / Gemini, the output is often wrapped in Markdown code blocks (```json ... ```) or accompanied by explanatory text; ② Copying from JavaScript object's console.log() may include trailing commas and single quotes; ③ Configuration files often use JSON5 / JSONC extended syntax (allowing comments, unquoted keys, multi-line strings, etc.); ④ Streaming responses or log truncation may break JSON mid-stream, missing the closing `}` or `"`. A JSON Repair tool scans the input text, identifies these typical issues and restores the content to standard JSON with a "minimum intrusion" principle while preserving original data semantics as much as possible.
At the implementation level, JSON Repair typically consists of two stages: ① Tolerant parse — using a state-machine based scanner rather than regex matching to process the character stream step by step, distinguishing syntax characters "inside strings" from "outside strings"; ② Canonical output — regenerating the result with `JSON.parse` + `JSON.stringify`, ensuring the output is 100% valid for any downstream strict parser. GeekFormat's JSON Repair tool completes the entire repair flow locally in the browser, never sending the original content to any server, suitable for processing sensitive API responses, internal configuration files, and AI model output.
Use Cases
- AI/LLM output cleanup: one-click convert Markdown-wrapped, explanatory-text-augmented and trailing-comma-laden JSON returned by ChatGPT/Claude into standard JSON
- Interface debugging and troubleshooting: when API responses are truncated by gateway or network issues, quickly complete brackets and strings to locate the original data structure
- JavaScript object literals copied from console: one-stop fix for single quotes, trailing commas, and unquoted keys
- Configuration file cleaning: strip comments from JSON5/JSONC to obtain standard JSON, ready for unified downstream consumption
- Log & clipboard data repair: quickly standardize JSON snippets containing comments, special whitespace, or truncation
- Data migration & script pre-processing: add a repair step in the data migration pipeline to prevent a few invalid JSONs from blocking an entire ETL batch
How to Use
- Paste the error-containing, Markdown-wrapped, or truncated JSON content into the left input box, or click "Sample" to load a typical broken JSON, or upload a .json/.txt file
- The tool automatically detects and fixes common syntax issues; the right output area shows the formatted standard JSON and the count of each class of problem repaired
- If red error messages remain, you can manually edit the input and re-trigger repair (Mac: ⌘+Shift+R, Windows: Ctrl+Shift+R)
- After confirming the structure is correct, click "Copy" to put the repaired result in the clipboard, or click "Download" to save as repaired.json for further formatting, validation, etc.
Features
- Covers 7 common syntax errors: trailing commas, single quotes, unquoted keys, unclosed strings, comments, missing brackets, Markdown code block wrappers
- AI output cleanup optimized: auto-strip ```json wrappers and surrounding explanatory text; recognizes typical output from ChatGPT, Claude, Gemini and other LLMs
- JSON5/JSONC compatible: parses extended syntax including comments, loose quotes, and special whitespace (e.g. invisible Unicode characters)
- Truncated JSON smart completion: handles truncated API responses and missing closing braces by auto-completing missing brackets and quotes
- Repair problem visualization: auto-stats and shows the count of each class of problem repaired for easy audit and human review
- Local processing for privacy: parsing, repair, and formatting all happen locally in the browser, no input sent to any server
- Seamless hand-off to formatting: repaired standard JSON can directly enter JSON Formatter, Schema Validator, or code generator as next steps
- File & sample loading: supports uploading .json/.txt files or clicking to load a sample for quick verification of repair effects
Code Examples
Programmatic repair with the jsonrepair JavaScript library
javascript// npm install jsonrepair
import { jsonrepair } from 'jsonrepair';
const broken = `{
name: 'Alice',
age: 30,
tags: ['dev', 'writer',], // trailing comma + comment
}`;
try {
const fixed = jsonrepair(broken);
const obj = JSON.parse(fixed);
console.log(obj);
// => { name: 'Alice', age: 30, tags: ['dev', 'writer'] }
} catch (err) {
console.error('Still unrepairable:', err.message);
}Programmatic repair with the jsonrepair Python library
python# pip install jsonrepair
from jsonrepair import jsonrepair
import json
broken = '''{
name: "Alice",
age: 30,
tags: ["dev", "writer",], // trailing comma + comment
}'''
fixed = jsonrepair(broken)
obj = json.loads(fixed)
print(obj)
# => {'name': 'Alice', 'age': 30, 'tags': ['dev', 'writer']}Quick trailing-comma fix with jq + sed (emergency only)
bash# Strip trailing commas from objects/arrays (emergency option; does NOT handle comments / single quotes) # For complex scenarios, use a dedicated library like jsonrepair sed -E 's/,([ \t]*[}\]])/\1/g' broken.json > clean.json # Validate the cleaned output jq . clean.json >/dev/null && echo 'JSON is valid'
FAQ
What is the difference between JSON Repair and JSON Formatter?
JSON Formatter only re-formats JSON that is already legal but has inconsistent indentation or spacing. JSON Repair, on the other hand, specifically handles JSON with syntax errors: it first corrects structural problems like trailing commas, single quotes, comments, and missing brackets, then outputs standard format. When a formatter tool throws SyntaxError, you should reach for JSON Repair first.
Which common JSON syntax errors does the tool support fixing?
The tool includes intelligent repair algorithms for the following high-frequency issues: 1) Trailing commas; 2) Single quotes in place of double quotes; 3) Unquoted keys; 4) Unclosed strings; 5) JavaScript line/block comments; 6) JSON wrapped in Markdown code blocks; 7) Missing closing braces/brackets due to truncated endings.
Why is JSON output from AI or LLMs often non-standard?
Large language models (e.g. ChatGPT, Claude, Gemini) frequently produce JSON wrapped in Markdown (```json ... ```), with explanatory prefix/suffix text, trailing commas, comments, or with incomplete structure due to token truncation. JSON Repair is specifically optimized for these scenarios to one-click clean AI output into valid JSON.
Is the repaired JSON structurally always identical to the original data?
The repaired output is a valid JSON string conforming to the JSON standard; the data semantics are preserved in the vast majority of cases. However, since repair is based on heuristic rules, in extremely broken or ambiguous scenarios (e.g. multiple missing commas on the same line) it may deviate slightly from the original intent. We recommend running Schema Validation or human review for critical data.
Why not just use Python json.loads or JavaScript JSON.parse directly?
Native parsers can only throw errors on SyntaxError, not perform repair. JSON Repair is a tolerant layer that sits in front of native parsers: it first attempts to fix the text, then hands it to the native parser, ensuring the final output is consumable by any strict JSON parser. The same idea can be applied as pre-processing in production environments on the server side.
Are comments in JSON5 / JSONC preserved?
No. Comments are part of the JSON5 extended syntax, not standard JSON. The tool strips them to ensure the output conforms to standard JSON. If you wish to keep comments, continue using JSON5 source files or the JSONC toolchain. If you need to convert JSON5 to standard JSON, this tool does it directly.
Can truncated JSON (e.g. streaming output cut off) be repaired?
Yes. The tool attempts to match missing right parentheses, square brackets, and string-closing quotes, preserving as much identified content as possible. Note: if the truncation point falls inside a string literal, you may need to manually supply the missing key characters.
Is there any data loss after repair?
In common repair scenarios (removing trailing commas, adding quotes, completing brackets, stripping comments) the data semantics are fully preserved. In rare cases, when the original content has irreversible ambiguity (e.g. nesting level destroyed), the tool will repair as conservatively as possible and output the original as-is; it will not actively delete fields or keys.
Can I batch-repair multiple JSONs?
This tool repairs one input at a time. For batch scenarios, we recommend running the underlying algorithm locally in a script (e.g. Python's jsonrepair library or the josdejong/jsonrepair npm package), then importing the result into this tool for human verification and formatting.
Do I still need to do formatting and Schema Validation after repair?
Recommended. Repair primarily addresses syntax-level errors; formatting and Schema Validation ensure readability and business correctness. The output of the repair tool seamlessly connects to GeekFormat's JSON Formatter, Schema Validator, and code generators.
Will the tool upload my JSON to a server?
No. All parsing, repair, and formatting happen locally in the browser; neither input nor intermediate results are sent to any server. Works offline, suitable for handling sensitive JSON (e.g. production environment API responses, internal configurations).
Can I fix the repair strategy used each time?
This tool enables all common repair rules by default to maximize success rate. If you need fine-grained control over rules for a specific language or team, you can use the jsonrepair library in your production environment and selectively enable or disable specific rules. This tool's output can also serve as a standardized input for downstream validation.
Troubleshooting
"Unable to repair this JSON" error
Cause: the input text has severe structural damage, such as multiple missing brackets, truncated string literals, or corrupted character set. Solution: open the original file in a plain-text editor first, confirm the encoding is UTF-8 without BOM, and it's not a compressed binary; if the data came from an API response, contact the upstream to complete it; for extremely broken data sets, use the source file directly.
Fields moved to the wrong position after repair
Cause: the original text contained JSON syntax characters (e.g. //, /*, }) inside comments or string literals, misleading the parser; or the nesting level is so deep that bracket matching is off. Solution: manually escape the // and /* inside strings; for deeply nested data, add temporary outer brackets or line breaks before re-running repair.
Explanatory text in AI output is not stripped
Cause: AI output often begins/ends with natural language (e.g. "Here is the result:") and may span multiple lines. Solution: use a text editor to delete the text outside the JSON block, keeping only the content within the outermost ```json wrapper; if the tool still cannot recognize it, manually add the outermost { } before re-running repair.
Size didn't change after repair, or some characters were replaced
Cause: the original contained backslashes, Unicode escapes, or HTML entities, which the tool re-escaped according to JSON rules. Solution: check whether the original was nested inside a JS string; if it's in an HTML page, decode HTML first; more characters after escaping is normal.
Browser shows "Out of memory" or freezes
Cause: a single input over 5–10 MB puts significant memory pressure on the browser. Solution: split the data into smaller batches (1–2 MB each); or use the jsonrepair library on the server side for streaming; a small difference between repaired result and original is normal.
Schema validation still reports errors after repair
Cause: JSON Repair only fixes syntax-level errors; it doesn't enforce business field names, types, or values against the Schema. Solution: use GeekFormat's JSON Schema Validation tool to check field constraints; locate specific fields by error and correct them manually.
Glossary
- JSON
- JavaScript Object Notation, a lightweight key-value based data interchange format defined in RFC 8259. De-facto standard for REST APIs, configuration files, and logs.
- RFC 8259
- The IETF official JSON specification, defining the strict syntax for valid JSON — all keys must be double-quoted, only a limited set of characters in strings need escaping, comments and trailing commas are not allowed.
- JSON.parse
- The strict JSON parser built into JavaScript and modern browsers, following RFC 8259. It throws SyntaxError on any syntax error and cannot perform tolerant repair.
- JSON5
- An extended syntax for JSON (non-standard), allowing unquoted keys, single-quoted strings, comments (// and /* */), trailing commas, hexadecimal numbers, etc. Easier for humans to write but incompatible with JSON.parse.
- JSONC
- JSON with Comments, a generic name used by editors like VS Code for JSON config files with comments (e.g. tsconfig.json). Effectively an alias for JSON5.
- Trailing Comma
- An extra comma after the last element of an object or array. Allowed in JavaScript but prohibited by JSON standard — the most common syntax error from LLM output and console.log() copies.
- Markdown Code Block
- A code snippet wrapped in three backticks (```). LLMs often auto-wrap JSON output in ```json ... ```; pasting directly to JSON.parse() will fail.
- Tolerant Parser
- A parser that attempts to recover and continue parsing when encountering syntax errors. The core engine of a JSON Repair tool, distinct from strict JSON.parse.
- SyntaxError
- The syntax error exception thrown by JavaScript. Any strict JSON parser throws this when receiving input that doesn't conform to RFC 8259.
- Canonical JSON
- JSON regenerated via parse + stringify, with stable key order, no extra whitespace, and 100% compatibility with standard parsers. The final output format of a JSON Repair tool.
Common JSON Repair Error Types with Examples
| Error Category | Before | After | Repair Method |
|---|---|---|---|
| Trailing comma | { "a": 1, } | { "a": 1 } | Remove the comma after the last element |
| Single quotes | { 'a': 1 } | { "a": 1 } | Replace all single quotes with double quotes |
| Unquoted keys | { a: 1 } | { "a": 1 } | Add double quotes around the key |
| Line comments | { // comment
"a": 1 } | { "a": 1 } | Strip // whole-line comments |
| Block comments | { /* block */ "a": 1 } | { "a": 1 } | Strip /* */ block comments |
| Markdown wrapper | ```json
{ "a": 1 }
``` | { "a": 1 } | Remove ```json and ``` wrappers |
| Unclosed string | { "a": "hello } | { "a": "hello" } | Add missing string-closing quote |
| Missing bracket | { "a": 1 | { "a": 1 } | Stack-match to add missing closing brace/bracket |
JSON Repair vs JSON Formatter vs JSON Schema Validation
| Tool | What it solves | Input requirement | Failure mode |
|---|---|---|---|
| JSON Repair | Convert syntax-error JSON to valid JSON | Tolerant, accepts non-standard JSON | Errors when too broken to guess structure |
| JSON Formatter | Reformat valid JSON | Must be already valid JSON | SyntaxError thrown directly |
| JSON Compress | Strip whitespace, reduce size | Must be already valid JSON | SyntaxError thrown directly |
| JSON Schema Validation | Check field types/values vs business rules | Must be already valid JSON | Lists each field violating rules |
| JSON Merge / Sort | Multi-source merge / key sort | Must be already valid JSON | SyntaxError thrown directly |
Authoritative References
- JSON Compress
- CSV to JSON
- JSON to CSV
- JSON Diff
- JSON Escape / Unescape
- JSON Flatten
- JSON Formatter
- JSON Generator
- JSONPath Query
- JSON Merge
- JSON Repair
- JSON Schema Validator
- JSON Sort
- JSON Stringify
- JSON to HTML Table
- JSON to Java
- JSON to Markdown
- JSON to SQL
- JSON to TOML
- JSON to TypeScript
- XML to JSON
- JSON to XML
- YAML to JSON
- JSON to YAML
- JSON to Python
- JSON to Go
- JSON to Rust
- JSON to Swift
- JSON to C#
- JSON to C++
- JSON to PHP