Fix Broken JSON from AI Output
Operator: Abdulla Al Fahad. How tools are built and checked
You asked a language model for JSON and got something close: the object wrapped in a ```json fence with a friendly sentence above it, keys without quotes, a comma after the last item, True where JSON wants true, or a reply that simply stops halfway through the third record because it ran out of output length. JSON.parse rejects all of it, and finding the fault by eye in a few hundred lines is slow.
This tool reads the reply the way a careful person would, fixes the mistakes that have one obvious correction, and lists every change with the line and column where it was made. Then it hands the result to JSON.parse. If the JSON now parses, you get it formatted and ready to copy; if not, you see exactly where the remaining problem is. It never makes up a value to fill a gap.
Key features
- Removes a Markdown code fence and the chat text before and after it
- Changes single-quoted strings to double quotes, escaping any double quotes inside them
- Quotes bare keys, including Python-style number keys such as {1: "a"}
- Drops trailing commas before } and ] and removes // and /* */ comments
- Turns True, False and None into true, false and null, and NaN, Infinity and undefined into null, each one reported
- Adds a comma that is missing between two items on separate lines
- Escapes raw line breaks and tabs inside strings
- Closes output that was cut off: an open string, then each open array and object, reported as "Closed N brackets"
- A change list with the line and column of every fix in your input (fixes of one kind inside the same string share an entry; the first 200 entries are shown in full, with totals by kind), and a pointer to any error that remains
Pulling the JSON out of a reply intact
Input can be the whole reply, prose included, pasted or loaded from a .json or .txt file of up to 5 MB. When the text contains Markdown code blocks, the first one tagged json is read; failing that, the first block that contains a { or [. Without a fence, reading starts at the first { or [ and stops where that value closes, so text after it is dropped and reported.
The result is standard JSON. Strings and numbers are copied exactly as written, not parsed and re-printed, so an ID like 12345678901234567890 keeps all 20 digits and an escape such as \u00e9 stays as written. You can lay it out with 2 spaces, 4 spaces, tabs or on one line. Output nested more than 100 levels deep is always shown on one line, since indentation would make it enormous.
How it works
The scanner walks the text once, keeping a stack of the objects and arrays it is inside and what it expects next: a key, a colon, a value, or a comma or closing bracket. Each mistake is fixed at the moment it is met. A comma is looked past before it is written, so a comma followed by } or ] is dropped rather than emitted. When the scanner expects a comma but finds the start of a new item on the next line, it adds the comma and notes it; on the same line it does not guess.
Inside strings, a raw line break becomes \n and a raw tab \t. A double quote that is followed by more words rather than a comma, colon or bracket, as in "He said "hi" to me", is treated as part of the text and escaped. That guess is checked: if it would leave the string running to the end of the input, the string is read again without it. A backslash that does not start a JSON escape, like the \d in a regular expression, is doubled so the backslash survives as text, and \' becomes a plain apostrophe.
At the end of the input, anything left open is closed. An unfinished string is closed where it stops. An entry with a key but no value, a dangling comma, or a word cut short such as fals is removed instead of completed, and the message says what was dropped. Then one closing bracket is added for each open array or object, innermost first.
When the scanner meets something with no single safe fix, such as an unquoted text value or two items on one line with no comma between them, it stops, notes the position, and copies the rest unchanged. JSON.parse then reports the remaining error, and the page shows its line and column in the repaired text with the line itself and a caret under the fault.
Common use cases
- Parsing structured answers in a script when the model sometimes adds a sentence before the JSON
- Rescuing a long extraction run whose last response was cut off at the output limit
- Converting a Python dict that a notebook printed with print() into JSON for another program
- Cleaning a JavaScript object literal copied from source code so a JSON tool will accept it
- Checking quickly why a model's tool-call arguments fail to parse, with the exact position of the fault
How to use this tool
- Paste the model's reply as it came, code fence and all, or load the .json or .txt file you saved it in. Use sample loads a cut-off order record that needs eleven kinds of fix.
- Read the status line: valid JSON after a number of changes, already valid, or still not valid.
- Open the change list and skim it. Each line gives the position in your input and what was done there.
- If the input was cut off, check the last item in the result: it may be missing fields or end mid-word.
- If the result still does not parse, fix the spot the error box points to in your input; the repair runs again as you type.
- Choose a layout, then copy the result or download it as a .json file.
Example
Reply with a fence, a bare key, a Python literal and a trailing comma
Here is the record:
```json
{"sku": "MUG-01", qty: 2, "gift": False, "notes": "fragile, wrap twice",}
```
Anything else?Repaired JSON and the six changes listed
{
"sku": "MUG-01",
"qty": 2,
"gift": false,
"notes": "fragile, wrap twice"
}
1:1 Removed the text before the code fence: "Here is the record:".
2:1 Removed the Markdown code fence ```json and its closing fence.
3:19 Put double quotes around the key qty.
3:35 Changed False to false.
3:72 Removed a trailing comma before }.
5:1 Removed the text after the code fence: "Anything else?".Tips for best results
- Paste the reply unedited. The fence and the surrounding sentences are removed for you, and trimming by hand risks cutting a bracket.
- When the status says the input was cut off, compare the last record with the others before using it.
- If repair stops at an unquoted word, it is usually a text value that needs quotes; add them in the input and the rest is repaired.
- For a reply with several JSON blocks, paste one block at a time; only the first is read.
- Watch the notes under the status line: a repeated key or a number too long for JavaScript is flagged even when the JSON parses.
Common pitfalls
A cut-off reply loses whatever was never written. In {"rows": [{"id": 1, "city": "Leeds"}, {"id": 2, "city": "Yo the result keeps "Yo" as the city, because that is all the input contains. The repair says the last value may be incomplete; it cannot know the word was York.
Missing commas are only added between items on separate lines. {"a": 1 "b": 2} on one line stops the repair, because a missing comma and a stray character look the same there.
Unquoted text values are not quoted for you. {"status": active} could mean the string "active" or a variable named active, so the repair stops and leaves it to you.
Numbers in non-JSON forms such as 007, .5, +1 or 0x1F are left alone and reported as the remaining error rather than reinterpreted.
The inner-quote rule is a judgement. A quote followed by more text is treated as part of the string, so ["a" 1, "b"], which is missing a comma after "a", comes out as one string, a" 1, "b. The change list records these escapes as one entry per string, such as "Escaped 2 double quotes inside a string", placed at the first of them, so check every string it names.
Common errors and how to fix them
- "No JSON object or array was found."
- The text has no { or [ and is not a single JSON value on its own, or it opens with a word that is not true, false or null. Check that you pasted the model's answer rather than your prompt, and that the JSON part is included.
- "Still not valid JSON" with a stop note in the change list.
- Repair met something it would have to guess at. The stop note gives the position in your input; fix it there, for example by adding quotes around a text value or a comma between two items on the same line, and the repair runs again.
- "This reply is too long to repair here: the limit is 5 MB of text."
- Paste only the JSON part of the reply, or split a very large array into several pastes and join the repaired parts afterwards.
- "…contains binary data, so it cannot be AI output text."
- The file has NUL bytes near the start, so it is not a text file. Save the reply from the chat or your script as a .json or .txt file and load that one.
Best practices
- Ask the model for JSON only, with no fence and no commentary; the repair is a safety net, not a substitute for a clear instruction.
- Keep the change list in mind when a value looks odd: a null that you did not expect usually came from NaN, None or undefined.
- Validate repaired output against your schema before loading it into anything that matters.
- Treat a reply that needed brackets closed as partial and re-request the missing records.
What "never invents values" means here
Every fix either removes something that JSON does not allow (a fence, a comment, a trailing comma), rewrites a token into its JSON spelling (True to true, 'text' to "text"), or adds punctuation that has only one possible form (a closing bracket, a comma between lines). No key, string or number is created. Where a value would have to be made up, as with a key at the very end that has no value, the key is removed and the removal is listed.
NaN, Infinity and undefined become null because JSON has no spelling for them; that loses the difference between them, so each replacement is listed with its position.
Where the work happens
While you work, the tool holds the pasted text, the name of a loaded file, your layout choice, and the repaired result with its change list in the tab's memory. The repair and the JSON.parse check are done by the page's own script. The tool has no code that uploads the text or saves it to browser storage, so a reload empties the box. Download .json saves the repaired JSON as a file, named after the file you loaded or ai-output-repaired.json for pasted text, and Copy places it on your clipboard.
Frequently asked questions
Will it change JSON that is already valid?
No. Valid input passes through with zero changes; the result only differs in layout, if you picked one.
Does it handle a Python dict printed with print()?
Yes. Single quotes, True, False and None are the differences, and all of them are converted. A tuple such as (1, 2) is not, because JSON has no tuple; replace the parentheses with square brackets first.
Why are long numbers kept exactly?
The result is re-indented token by token instead of being parsed and printed again, so digits beyond what a JavaScript number can hold are not rounded. A note warns that a program reading the file may still round them.
What does "Closed 2 brackets" mean?
The input ended while one array and one object were still open, so ] and } were added at the end. For {"a": [1, 2 the result is {"a": [1, 2]}.