JSON5 Parsing Model Output: Parse First, Repair Second

What a JSON5 parser accepts from text a language model returns, what it rejects, and when to reach for a repair library.

Ask a language model for JSON and you often get something close: single quotes, a trailing comma, a Markdown fence, a sentence before the object, or text that stops in the middle. A strict parser rejects all of it. A JSON5 parser forgives some of it, and a repair library forgives nearly everything, but it does so by guessing.

We wrote fourteen small samples, ran each one through JSON.parse, JSON5.parse and jsonrepair, and kept the real results. The table, a tested recipe and one case where the repair is wrong are below.

Messy text on a conveyor passing three gates labeled parse, lenient parse and repair before reaching a clean data tray

TL;DR: Parse first, repair second. Try JSON.parse, then JSON5.parse, and only then a repair library, and check the shape of the result every time. In our runs JSON5.parse handled single quotes, trailing commas, comments and unquoted keys, but threw on code fences, surrounding prose, cut-off text, Python True and None, and missing commas. jsonrepair accepted all fourteen samples, and for four of them the output was wrong or lossy. Tested with json5 2.2.3 and jsonrepair 3.15.0 on 12-01-2026.

Checklist icon

The Rule: Parse First, Repair Second

A model returns text, not data. Your code has to turn that text into an object it can trust, and there are three tools for the job, from strictest to most forgiving.

  1. JSON.parse is built in, fast and exact. If it works, the text was real JSON and nothing was guessed.
  2. JSON5.parse follows a published grammar. It reads a defined set of extra syntax and rejects everything else. The rules are the same every time, so you can say exactly what it accepts.
  3. A repair library such as jsonrepair reads text that is not valid in any grammar and decides what the writer probably meant. It does not follow a standard. It makes choices.

Go down that list only as far as you must. Each step accepts more input and gives you less certainty about what the result means. A guess is acceptable when a person will read the output or when a schema check follows. It is risky when the result drives money, permissions or deletions. Whatever step produced the value, finish with a shape check, as the recipe below does.

This page makes no claim about how often a model makes any mistake. It only shows what each parser does with each one.

Test icon

Fourteen Samples, Three Parsers

We installed json5 2.2.3 and jsonrepair 3.15.0 in an empty folder, wrote one hand-made sample per defect, and ran each through all three parsers on Node.js 24.22.1 (npm 11.6.4) on 12-01-2026. Error messages are copied from the runs. For jsonrepair the cell shows the repaired text, which we then checked with JSON.parse. \n stands for a newline inside a sample.

Sample (defect)JSON.parseJSON5.parsejsonrepair
Clean JSON (control)
{"name": "Ada", "age": 36}
ParsedParsed: {name:'Ada',age:36}Repaired: {"name": "Ada", "age": 36}
Single quotes
{'name': 'Ada', 'age': 36}
Error: Expected property name or '}' in JSON at position 1 (line 1 column 2)Parsed: {name:'Ada',age:36}Repaired: {"name": "Ada", "age": 36}
Trailing commas
{"a": 1, "b": [1, 2, 3,],}
Error: Unexpected token ']', ..." [1, 2, 3,],}" is not valid JSONParsed: {a:1,b:[1,2,3]}Repaired: {"a": 1, "b": [1, 2, 3]}
Comments
{\n // the user\n "name": "Ada", /* years */ "age": 36\n}
Error: Expected property name or '}' in JSON at position 4 (line 2 column 3)Parsed: {name:'Ada',age:36}Repaired: {\n \n "name": "Ada", "age": 36\n}
Unquoted keys
{name: "Ada", age: 36}
Error: Expected property name or '}' in JSON at position 1 (line 1 column 2)Parsed: {name:'Ada',age:36}Repaired: {"name": "Ada", "age": 36}
NaN and Infinity
{"x": NaN, "y": Infinity}
Error: Unexpected token 'N', "{"x": NaN, "y": "... is not valid JSONParsed: {x:NaN,y:Infinity}Repaired: {"x": "NaN", "y": "Infinity"}
Markdown code fence
```json\n{"name": "Ada"}\n```
Error: Unexpected token '`', "```json {""... is not valid JSONError: JSON5: invalid character '`' at 1:1Repaired: \n{"name": "Ada"}\n
Prose before and after
Here is the JSON you asked for:\n{"name": "Ada"}\nLet me know if you need changes.
Error: Unexpected token 'H', "Here is th"... is not valid JSONError: JSON5: invalid character 'H' at 1:1Repaired: [\n"Here is the JSON you asked for:",\n{"name": "Ada"},\n"Let me know if you need changes."\n]
Cut-off text
{"name": "Ada", "tags": ["a", "b
Error: Unterminated string in JSON at position 32 (line 1 column 33)Error: JSON5: invalid end of input at 1:33Repaired: {"name": "Ada", "tags": ["a", "b"]}
Python True and None
{"active": True, "owner": None, "score": 9}
Error: Unexpected token 'T', ...""active": True, "own"... is not valid JSONError: JSON5: invalid character 'T' at 1:12Repaired: {"active": true, "owner": null, "score": 9}
Missing comma
{"a": 1 "b": 2}
Error: Expected ',' or '}' after property value in JSON at position 8 (line 1 column 9)Error: JSON5: invalid character '\"' at 1:9Repaired: {"a": 1, "b": 2}
Curly quotes
Curly double quotes (U+201C and U+201D) around the key and the value
Error: Expected property name or '}' in JSON at position 1 (line 1 column 2)Error: JSON5: invalid character 'U+201C' at 1:2Repaired: {"name": "Ada"}
Ellipsis placeholder
{"items": [1, 2, 3, ...]}
Error: Unexpected token '.', ..."[1, 2, 3, ...]}" is not valid JSONError: JSON5: invalid character '.' at 1:22Repaired: {"items": [1, 2, 3 ]}
Raw newline in a string
{"text": "line one\nline two"}
Error: Bad control character in string literal in JSON at position 18 (line 1 column 19)Error: JSON5: invalid character '\n' at 2:0Repaired: {"text": "line one\nline two"}

Two cells need a second look. JSON5.parse returned NaN and Infinity for the numeric sample, which is valid JSON5, but JSON.stringify of that object prints {"x":null,"y":null}. And jsonrepair turned those two words into the strings "NaN" and "Infinity". See the guess section.

Yes icon

What a JSON5 Parser Accepts

Four defects in the table parsed cleanly with JSON5.parse, and all four are part of the JSON5 grammar (the 1.0.0 specification lists them):

  • Single-quoted strings. {'name': 'Ada'} parsed to the same object as the double-quoted form.
  • Trailing commas in objects and arrays, including [1, 2, 3,],}.
  • Comments, both // and /* */. A model that explains a field in a comment no longer breaks the parse.
  • Unquoted keys that are valid identifiers, such as {name: "Ada"}.

The same grammar also allows hex numbers, a leading plus sign, Infinity and NaN. That last pair is the one to watch. It parses, but JSON has no way to write it, so a later JSON.stringify silently turns both into null. If your data must never contain them, check for them after parsing. Everything JSON5 adds is listed in the syntax reference, and the library API is in the JavaScript guide and the Node.js guide.

No icon

What It Does Not Accept

A JSON5 parser is a parser for JSON5, not a tolerant text scanner. Eight of the fourteen samples are outside the grammar, and JSON5.parse threw on every one:

  • Markdown code fences. The text starts with three backticks, so the error is invalid character '`' at 1:1. Strip the fence before parsing.
  • Prose before or after the object. A sentence is not part of any JSON grammar. Extract the object first or ask for a response that is only data.
  • Cut-off text. invalid end of input at 1:33. A parser cannot invent the missing part.
  • Python True, False and None. Only lowercase true, false and null exist in JSON and JSON5.
  • Missing commas between members. {"a": 1 "b": 2} is two values with nothing between them.
  • Curly quotes used as string delimiters, a literal ... placeholder, and a raw newline inside a string. JSON5 allows a backslash before the newline, not a bare one.

Two of these are cheap to handle without any library. A fence is a three-line regular expression, and an object buried in prose can often be cut out by finding the first opening brace and its matching close. The rest need real repair or a retry.

Code icon

A Tested Recipe

The function strips a code fence, then tries JSON.parse, JSON5.parse and jsonrepair in that order. After each step it runs your validator and moves on if the shape is wrong. It returns which step worked, so you can log how often you needed each one. Run on Node.js 24.22.1 with npm install json5 jsonrepair.

const JSON5 = require('json5'); const { jsonrepair } = require('jsonrepair'); function stripFence(text) { const m = text.trim().match(/^```[a-zA-Z0-9]*\s*\n([\s\S]*?)\n?```$/); return m ? m[1] : text; } function parseModelJson(raw, isValid) { const text = stripFence(raw).trim(); const steps = [ ['json', (t) => JSON.parse(t)], ['json5', (t) => JSON5.parse(t)], ['repair', (t) => JSON.parse(jsonrepair(t))], ]; const errors = []; for (const [name, parse] of steps) { try { const value = parse(text); if (isValid(value)) return { value, method: name }; errors.push(name + ': parsed, but the shape is wrong'); } catch (e) { errors.push(name + ': ' + e.message); } } throw new Error('No usable JSON.\n' + errors.join('\n')); } const isUser = (v) => v !== null && typeof v === 'object' && !Array.isArray(v) && typeof v.name === 'string' && Number.isInteger(v.age);

We ran it on seven inputs. The method column is the first step whose result passed isUser:

InputMethodResult
Clean JSONjson{"name":"Ada","age":36}
Fenced JSONjsonsame object, fence removed first
{name: 'Ada', age: 36, // note }json5{"name":"Ada","age":36}
Python False inside the objectrepair{"name":"Ada","age":36,"admin":false}
Sentence, object, sentencenoneFailed: repair returned an array, and the shape check rejected it
"age": "thirty-six"noneFailed: every step parsed it, none passed the shape check
I cannot help with that.noneFailed: repair turned the sentence into a JSON string, and the shape check rejected it

The shape check is what keeps the repair step honest. Without it the sentence-around-object input would have returned an array of three items and the refusal text would have returned a string, and both are valid JSON. For a real project, replace isUser with a schema; the schema validation guide shows how, and the online validator lets you check a sample by hand.

Warning icon

Repair Guesses, and Guesses Can Be Wrong

jsonrepair never refused a sample in our run. That is a strength when you need an answer and a risk when the answer is wrong, because it returns valid JSON either way. These are real outputs where the repair changed or invented meaning. Four come from the table above and three from extra one-line runs on the same day:

SampleRepaired toWhat went wrong
{"id": 12 (cut off){"id": 12}The writer may have meant 120 or 1234. The repair keeps the digits it saw.
{"price": 19. (cut off){"price": 19.0}The missing decimals are filled with zero, not recovered.
{"name": "Ada", "tags": ["a", "b (cut off inside a string){"name": "Ada", "tags": ["a", "b"]}The real value may have been a longer word. The result looks complete.
Sentence, object, sentencean array of three items: the first sentence, the object, the last sentenceValid JSON, wrong shape. Your code expected an object.
{"x": NaN, "y": Infinity}{"x": "NaN", "y": "Infinity"}Numbers became strings. A later comparison or sum behaves differently.
{"items": [1, 2, 3, ...]}{"items": [1, 2, 3 ]}The placeholder is dropped. The list now looks complete.
I cannot help with that.the JSON string "I cannot help with that."Plain text became "data".

Repair guesses. It can change meaning, and it hides the fact that it did. The first cut-off row is the clearest case: {"id": 12 became a complete, valid object with an id the model may never have sent. The library's README lists the problems it can fix and says it throws a JSONRepairError when it cannot solve one. We found nothing there about a warning when it makes a choice, so build your own guard: log which step produced each value, keep the raw text, and treat output from the repair step as lower trust than output from the first two.

Cut-off text is the case to treat most carefully. If the response stopped early, the better fix is usually to request it again or to ask for a smaller piece, not to repair what arrived.

Security icon

Model Output Is Untrusted Text

Treat model output like any text from outside your system. A prompt can be steered by the content it reads, so an object that looks like your schema may carry values you did not intend. Parse it, validate it against a schema, and never pass fields from it straight into a query, a file path or a permission check.

One parser detail applies directly to untrusted text. Versions of the json5 package from 2.0.0 up to but not including 2.2.2, and all versions before 1.0.2, did not guard the key __proto__ in JSON5.parse, which could set properties on the prototype of the returned object (CVE-2022-46175, GitHub advisory GHSA-9c47-m6qq-7p4h). The fix shipped in 2.2.2 and 1.0.2, and the version we tested is 2.2.3. Read the CVE-2022-46175 page and the wider security guide, and keep the dependency current.

Tools icon

When to Use a Repair Library

SituationUse
The text parses with JSON.parseNothing else. Done.
Only single quotes, comments, trailing commas or unquoted keys are wrongJSON5.parse. No guessing involved.
A fence or a sentence wraps the dataStrip the fence or cut out the object, then parse again.
Python constants, missing commas, curly quotes, cut-off textjsonrepair, then a shape check, and log that repair ran.
The result drives money, deletion or accessDo not repair. Reject and retry, or ask a person.
You want to look at a broken sample by handThe browser tool online repair, which uses jsonrepair.
Question icon

Common Questions

Is JSON5 enough to parse model output?

Only for the defects it was designed to allow: comments, trailing commas, single quotes and unquoted keys. In our samples it threw on fences, prose, cut-off text, Python constants and missing commas. Use it as the second step, not the last.

Why not repair everything?

Because repair guesses. It returned valid JSON for all fourteen samples, including a sentence that is not data, and it changed a cut-off number into a complete one. A strict parse that fails is information. A repair that succeeds can hide it.

Should I ask for JSON5 instead of JSON?

Not usually. The rest of your system probably expects JSON, and asking for plain JSON with no wrapper text is the clearest request. Accepting JSON5 on the way in is a cheap safety net, not a goal.

How do I know which step produced a value?

The recipe returns the method with the value. Log it. If the repair step runs often, fix the request or the response format instead of leaning on repair.

Does this work in Python or other languages?

We tested only Node.js. The grammar rules for JSON5 are the same everywhere, and the implementations list shows parsers in other languages, but we did not run repair libraries for them.

Sources

(6)
  1. JSON5 1.0.0 specification, the list of accepted syntax
  2. josdejong/jsonrepair, README: what it repairs and when it throws JSONRepairError (version 3.15.0 installed)
  3. json5/json5, the reference parser (version 2.2.3 installed)
  4. GitHub advisory GHSA-9c47-m6qq-7p4h, CVE-2022-46175, affected and patched versions
  5. MDN: JSON.parse, strict parsing and its errors
  6. RFC 8259, the JSON grammar that rejects the samples above

Tested with Node.js 24.22.1, npm 11.6.4, json5 2.2.3 and jsonrepair 3.15.0 on 12-01-2026. Last reviewed: December 1, 2026.