Position is where the parser gave up, not necessarily where the mistake is
This is the one concept you need before reading any JSON error; everything else follows from it. Here is JSON missing exactly one comma:
const text = '{\n "a": 1\n "b": 2\n}';
JSON.parse(text);
// SyntaxError: Expected ',' or '}' after property value in JSON at position 13 (line 3 column 3)
Position 13, line 3 column 3. What is actually there?
text[13]; // '"' — the opening quote of "b" on line 3
text.slice(8, 16); // ' 1\n "b"'
The error points at the opening quote of "b", while the comma you need to insert belongs at the end of line 2, index 10. The gap follows from how the parser works: having read "a": 1 it is in a state where only , or } is legal; it skips whitespace, reads a ", and only then establishes that — however normal everything before looked — it cannot continue here. So position is where continuation became impossible, and the real problem is somewhere before it. How far before depends on the kind of error.
Conversely, some errors point exactly at the culprit. A raw newline inside a string literal is one:
JSON.parse('{"a": "line1\nline2"}');
// SyntaxError: Bad control character in string literal in JSON at position 12 (line 1 column 13)
Index 12 is the \n itself. JSON forbids raw control characters (U+0000 to U+001F) inside strings — a newline must be written as the two characters \n — so the parser knows it is wrong the moment it reads it, with no need to look further.
Whether to search backwards or look right there depends on whether the message says “expected something and did not get it” or “read something that must not appear”. That distinction is worth reading before the position number.
One document, four Node versions, three different messages
Error text is not part of the specification. It varies by engine and version. Here is the same comma-less JSON from above, run on four Node versions:
| Runtime | Message |
|---|---|
| Node v18.12.1 (V8 10.2) | Unexpected string in JSON at position 13 |
| Node v20.0.0 (V8 11.3) | Expected ',' or '}' after property value in JSON at position 13 |
| Node v22.17.1 (V8 12.4) | Expected ',' or '}' after property value in JSON at position 13 (line 3 column 3) |
| Node v24.19.0 (V8 13.6) | Expected ',' or '}' after property value in JSON at position 13 (line 3 column 3) |
Four versions, three wordings. V8 10.x only says “a string turned up”; 11.x spells out what it expected; 12.x adds line and column; 13.x is word-for-word identical to 12.x. Position 13 is the only thing identical across all four — it is the parser’s actual state, and the wording is packaging. So when a troubleshooting article online quotes an error that does not match yours, check versions before doubting your JSON.
Change engine and the divergence widens. On macOS you can reach JavaScriptCore — the engine Safari uses — without installing anything, because osascript -l JavaScript runs on it:
osascript -l JavaScript -e 'try{JSON.parse("{\"a\": 1 \"b\": 2}")}catch(e){console.log(e.message)}'
# JSON Parse error: Expected '}'
Same JSON, and JavaScriptCore says JSON Parse error: Expected '}' — no position, no line, no column, nothing. I ran the whole test set through it and the pattern holds: JSC’s JSON Parse error: family never carries position information. A few side by side:
| Input | V8 (Node v22.17.1) | JavaScriptCore (macOS 26.5.2) |
|---|---|---|
{"a":1,} |
Expected double-quoted property name in JSON at position 7 (line 1 column 8) |
JSON Parse error: Property name must be a string literal |
{'a':1} |
Expected property name or '}' in JSON at position 1 (line 1 column 2) |
JSON Parse error: Single quotes (') are not allowed in JSON |
{"a": "x\ny"} |
Bad control character in string literal in JSON at position 8 (line 1 column 9) |
JSON Parse error: Unterminated string |
'' (empty) |
Unexpected end of JSON input |
JSON Parse error: Unexpected EOF |
The third row is the interesting one. For the same raw newline, V8 says “illegal control character in a string literal” and JSC says “unterminated string” — and from JSC’s point of view that is also true, since it considers the string to have ended at the newline. Both point at the same character and name different causes.
When a user reports “JSON parsing failed” but cannot give you a position, it is probably Safari. Asking them to reproduce in Chrome, or just getting the text and running it yourself, beats continuing the conversation.
V8 has two error families, and one of them has no position
Even staying inside Node, do not assume position is present. V8’s JSON errors come in two families with completely different formats:
JSON.parse('{"a": 1 "b": 2}');
// Expected ',' or '}' after property value in JSON at position 8 (line 1 column 9)
JSON.parse('{"a": @}');
// Unexpected token '@', "{"a": @}" is not valid JSON
The second is the Unexpected token message everyone has seen. It gives no position number, offering a snapshot of the source instead. On a long document the snapshot is truncated at both ends with ...:
JSON.parse('{"pad": "' + 'x'.repeat(300) + '", "a": @}');
// Unexpected token '@', ..."xx", "a": @}" is not valid JSON
That design is friendly for short documents — you can see it at a glance. For long ones it is awkward: the dozen characters inside the ... may occur hundreds of times in the file, so searching for them locates nothing. The test is simple: if the message contains Unexpected token 'X' followed by a quoted snippet, it is this family — do not try to regex a position out of it, there is none.
Translate the error into line, column and nearby code points
All of the above points at one conclusion: do not read these messages with your eyes. Write six lines that turn them into something you can act on.
function explain(text) {
try { JSON.parse(text); return 'parsed OK'; } catch (e) {
const m = /at position (\d+)/.exec(e.message);
const t = /Unexpected token '(.)'/.exec(e.message);
const pos = m ? Number(m[1]) : (t ? text.indexOf(t[1]) : -1);
if (pos < 0) return e.message + ' (cannot locate)';
const before = text.slice(0, pos);
const line = before.split('\n').length;
const col = pos - before.lastIndexOf('\n');
const codes = [...text.slice(Math.max(0, pos - 4), pos + 4)]
.map(c => 'U+' + c.codePointAt(0).toString(16).toUpperCase().padStart(4, '0')).join(' ');
return `${e.message}\n -> line ${line}, column ${col}, index ${pos}\n -> nearby code points: ${codes}`;
}
}
It handles both families: use position when present, otherwise take the character out of Unexpected token 'X' and indexOf it. Measured on three inputs:
input {"a": 1 "b": 2}
Expected ',' or '}' after property value in JSON at position 8 (line 1 column 9)
-> line 1, column 9, index 8
-> nearby code points: U+003A U+0020 U+0031 U+0020 U+0022 U+0062 U+0022 U+003A
input {"a": “1”}
Unexpected token '“', "{"a": “1”}" is not valid JSON
-> line 1, column 7, index 6
-> nearby code points: U+0061 U+0022 U+003A U+0020 U+201C U+0031 U+201D U+007D
input {"a":1}\n{"b":2}
Unexpected non-whitespace character after JSON at position 8 (line 2 column 1)
-> line 2, column 1, index 8
-> nearby code points: U+003A U+0031 U+007D U+000A U+007B U+0022 U+0062 U+0022
The line that actually solves problems is the last one. In the second input, U+201C and an ordinary U+0022 were both printed side by side in the original message ("{"a": “1”}") — and they look too similar for the eye to stop on, especially when the surrounding text is full of other punctuation. Break the suspect range into hexadecimal code points and invisible things have nowhere left to hide. The next section is entirely about those.
When you do not have Node to hand, the JSON formatter on this site shows whatever the browser engine threw, unmodified — which means it is subject to everything in this article. Open it in Chrome and you get position and line/column; open the same page in Safari, paste the same JSON, and you get one bare JSON Parse error. That is not a design choice in the tool; it is the difference between engines.
Four culprits your editor will not show you
BOM (U+FEFF). The three bytes ef bb bf at the start of a file. The nasty part is that fs.readFileSync(f, 'utf8') does not strip it, so parsing is guaranteed to fail while the file you open looks like a perfectly ordinary {:
// file contains BOM + '{"a":1}\n'
fs.readFileSync('bom.json')[0].toString(16); // 'ef' — first three bytes are ef bb bf
fs.readFileSync('bom.json', 'utf8').codePointAt(0); // 65279, i.e. U+FEFF, still there
JSON.parse(fs.readFileSync('bom.json', 'utf8'));
// SyntaxError: Unexpected token '', "{"a":1}
// " is not valid JSON
Those single quotes in the message are not empty — U+FEFF is between them. It has no width, so in a terminal it looks like an empty pair. The file’s trailing newline was also copied verbatim into the snapshot, which is why one error is printed across two lines. This is exactly what makes this error family hard to read: it prints the offending character literally, and the offending character is the invisible one.
The fix is to decode the bytes with TextDecoder rather than letting readFileSync produce the string. One option name here is the inverse of what it sounds like:
const raw = fs.readFileSync('bom.json');
new TextDecoder('utf-8').decode(raw).codePointAt(0); // 123, i.e. '{' — BOM consumed
new TextDecoder('utf-8', { ignoreBOM: true }).decode(raw).codePointAt(0); // 65279 — BOM retained
ignoreBOM: true does not mean “ignore the BOM and discard it”. It means “do not treat the BOM as a BOM, keep it as an ordinary character”. The default, false, is the behaviour you want. I have to re-check this every single time, which is partly why it is written down here.
Smart quotes (U+201C / U+201D, “ ”). Configuration snippets copied out of chat logs, Word documents or messaging apps carry these constantly. On a key versus on a value, V8 does not even use the same error family:
JSON.parse('{“a”: 1}'); // Expected property name or '}' in JSON at position 1 (line 1 column 2)
JSON.parse('{"a": “1”}'); // Unexpected token '“', "{"a": “1”}" is not valid JSON
The first says only “a property name belongs here” and never mentions quotes at all — because to the parser “ is simply an unrecognised character and it has no idea you intended it as a quote. Single quotes at least get dedicated wording (JSC says Single quotes (') are not allowed in JSON outright); smart quotes do not even get that.
Non-breaking space (U+00A0). The most common import from copy-pasting a web page. It has a boundary that must be stated clearly:
JSON.parse('{"a": 1}'); // SyntaxError: Unexpected token ' ', "{"a": 1}" is not valid JSON
JSON.parse('{"a": "x y"}'); // parses fine, gives { a: 'x y' }
In a structural position it is fatal; inside a string literal it is perfectly legal. JSON recognises exactly four whitespace characters — space, tab, newline, carriage return — and U+00A0 is not among them, so between a key and a value it is an illegal token. Inside a string anything but a control character is allowed, so there it is just another character. The second case is the more troublesome one precisely because it does not error: the data flows into a database carrying an invisible character, and then quietly fails some === comparison later.
Raw control characters in strings. The newline example appeared in the first section; tabs are the same family:
JSON.parse('{"a": "x\ty"}'); // Bad control character in string literal in JSON at position 8 (line 1 column 9)
These almost always come from assembling JSON by hand — dropping a multi-line log into a template literal instead of going through JSON.stringify(). This is the one of the four that is easiest to eliminate at source: do not hand-write JSON, let JSON.stringify() do the escaping. It turns newlines into \n and tabs into \t without ever missing one.
While we are here: reviver has nothing to do with locating errors
JSON.parse’s second argument is often mistaken for a parsing hook that can intervene when something fails. It cannot. On the same invalid JSON, with and without a reviver, the error is word-for-word identical:
JSON.parse('{"a": 1 "b": 2}');
// Expected ',' or '}' after property value in JSON at position 8 (line 1 column 9)
JSON.parse('{"a": 1 "b": 2}', (k, v) => v);
// Expected ',' or '}' after property value in JSON at position 8 (line 1 column 9)
The reason is that the reviver only starts work after parsing has fully succeeded: the parser builds the complete value first, then the reviver walks it bottom-up. I counted the calls — parsing {"a":1,"b":[2]} invokes the reviver 4 times with keys "a", "0", "b" and "" (that last empty string being the root value); parsing the invalid {"a":1,"b":} invokes it 0 times. In the face of a syntax error it never gets on stage. What a reviver is for is value-level work — turning ISO date strings into Date, large integers into BigInt — not debugging.
Files with hundreds of thousands of lines: bisection, and why the naive version fails
Past a certain size everything above stops working at once. I built a JSON array of 200,000 elements, 6,088,894 bytes, 200,003 lines, with a U+00A0 planted in element 137001. Pretty-printed, V8’s error is still usable:
Expected double-quoted property name in JSON at position 4135908 (line 137002 column 17)
Minify the same data onto one line — which is what almost every real API returns — and it becomes:
Expected double-quoted property name in JSON at position 3313904 (line 1 column 3313905)
Line 1, column 3,313,905. That coordinate is useless in any editor, and Safari will not even give you that much. This is where bisection belongs. But cutting the document in half directly does not work, so let me close that road first:
JSON.parse(text.slice(0, text.length >> 1));
// Unexpected end of JSON input
JSON.parse(text.slice(text.length >> 1));
// Unexpected non-whitespace character after JSON at position 27 (line 1 column 28)
Both halves fail, and neither failure is the U+00A0. The first half is missing its closing ], so it ends unexpectedly. The second is more interesting: the cut happened to land between two elements, so the parser read the one complete object at the start (27 characters) and stopped, then hit a comma at character 28 and reported “non-whitespace after JSON” — while the real culprit is thirty thousand elements away. JSON is a nested structure, so any cut breaks the pairing, which means “which half still fails” is permanently “both”, and that is no signal at all.
For bisection to work, the cut has to land on a structural boundary, and the outer container has to be restored afterwards. For an array, that means cutting between elements and appending a ]:
// each element occupies its own line in this file, so the separator is ",\n"
const items = text.slice(text.indexOf('[') + 1, text.lastIndexOf(']')).split(',\n');
const okPrefix = (k) => {
try { JSON.parse('[' + items.slice(0, k).join(',\n') + ']'); return true; }
catch { return false; }
};
let lo = 0, hi = items.length, steps = 0;
while (lo < hi) { const mid = (lo + hi) >> 1; steps++; okPrefix(mid) ? (lo = mid + 1) : (hi = mid); }
console.log(steps, 'iterations, bad element index', lo - 1, items[lo - 1]);
This searches for the first k whose prefix fails to parse, and that predicate is monotonic — if the first k elements are valid then so are the first k−1 — so bisection is sound. On that 200,000-element file it finished in 17 iterations and 471 ms, landing directly on index 137000, whose only non-ASCII code point is U+00A0. The iteration count is on the order of log₂(element count), so ten times the elements costs three or four more steps.
Finally, its actual scope — do not treat it as a universal hammer. When the error already gave you a position, use the position; bisection is redundant. It earns its keep in three situations: the engine gives no position at all (Safari, and parsers in other languages that say only “invalid”); the document is minified onto one line, so line/column degrades into a seven-digit column you cannot navigate to; or you do not have the original text — it was assembled from dozens of fragments, streamed off the network, or produced by some generator. In the first two cases bisection hands you the offending element, which is far more useful than a character offset. In the third it hands you which fragment, and that is usually the thing you actually wanted to know.