JSON.parse Unexpected Token: Trailing Commas, Comments and BOM
JSON is stricter than JavaScript and stops at the first byte it cannot read. Which rule each message names, and the parser to use when you cannot fix the producer.

Introduction & Quick Summary
Symptom. JSON.parse throws SyntaxError: Unexpected token } in JSON at position 42, or on a newer runtime SyntaxError: Expected double-quoted property name in JSON at position 42, or Unexpected non-whitespace character after JSON at position 5. The payload looks like ordinary JavaScript, and the same file loads in Node but not in the browser — or the reverse.
Cause. JSON is not JavaScript. It has no trailing commas, no comments, no single quotes, no unquoted keys, no undefined, NaN or Infinity, no \x escapes, and no BOM at the start. JSON.parse is also strict about where it stops: an NDJSON file with two objects, or a config prefixed with a BOM, fails with a position that points past the end of what you expected.
Fix. Fix the producer when you own it, and use the right parser when you do not: a JSON5/JSONC parser for hand-edited config, a line-by-line reader for NDJSON, and a BOM strip before JSON.parse for files from Windows tooling. Then give the result a type, because JSON.parse returns any and the compiler will not catch a missing field.
Core Mechanics, Signatures & Reproducible Setup
JSON.parse(text, reviver?) accepts exactly RFC 8259 JSON text. Anything else is a syntax error with a character offset:
JSON.parse('{"a": 1,}'); // SyntaxError: Expected double-quoted property name …
JSON.parse("{'a': 1}"); // SyntaxError: Expected property name or '}' in JSON
JSON.parse('{a: 1}'); // SyntaxError: Expected property name or '}' in JSON
JSON.parse('{"a": NaN}'); // SyntaxError: Unexpected token 'N'
JSON.parse('\uFEFF{"a":1}'); // SyntaxError: Unexpected token '\uFEFF'
JSON.parse('{"a":1}\n{"b":2}'); // SyntaxError: Unexpected non-whitespace character after JSONThe V8 version decides the wording, which matters when you grep logs for the message:
Node 18 (V8 10.x): Unexpected token } in JSON at position 7
Node 20+ (V8 11.2+): Expected double-quoted property name in JSON at position 7A runnable diagnostic that names the offending character instead of guessing:
function parseJson(text: string): unknown {
const clean = text.replace(/^\uFEFF/, ''); // BOM
try {
return JSON.parse(clean);
} catch (err) {
const e = err as SyntaxError;
const m = /position (\d+)/.exec(e.message);
const at = m ? Number(m[1]) : 0;
throw new Error(
`${e.message}\n ${JSON.stringify(clean.slice(Math.max(0, at - 20), at + 20))}\n` +
` ${' '.repeat(Math.min(at, 20))}^`,
);
}
}That single helper turns "unexpected token at 42" into the three characters around position 42, which is almost always the trailing comma or the unescaped quote.
Key Comparison Table
Which strictness rule produced which message:
| Input | Message fragment | Rule |
|---|---|---|
{"a":1,} | Expected double-quoted property name | No trailing commas |
{'a':1} | Expected property name or } | Keys and strings need double quotes |
{a:1} | Expected property name or } | Unquoted keys |
// note | Unexpected token / | No comments |
{"a":NaN} | Unexpected token 'N' | Only numbers, no NaN/Infinity |
{"a":undefined} | Unexpected token 'u' | undefined is not a JSON value |
\uFEFF{…} | Unexpected token '\uFEFF' | No BOM |
{…}\n{…} | Unexpected non-whitespace character after JSON | Exactly one top-level value |
"line\nbreak" | Bad control character in string literal | Newlines must be escaped |
{"a":"\x41"} | Bad escaped character | No \x, no \', no \v |
Parsers and what they accept:
| Parser | Accepts | Returns | Use for |
|---|---|---|---|
JSON.parse | Strict RFC 8259 | any | Everything you control |
json5 / JSON5.parse | Comments, trailing commas, single quotes | object | Hand-edited config |
jsonc-parser | Comments, trailing commas, preserves errors | AST / value | tsconfig.json, VS Code files |
ndjson / split('\n') | One value per line | stream of objects | Log and export files |
JSON.parse + strip-json-comments | Comments only | any | Legacy config files |
eval / new Function | Almost all JavaScript | value | Never with untrusted input |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Trailing comma from a generator or a human
The most common cause in 2026 is still a template that emits , after the last element. A producing-side fix is cheaper than a lenient parser everywhere:
// Broken
const body = `{"items": [${items.map((i) => JSON.stringify(i)).join(',')},]}`;
// Fixed: join, no trailing separator
const body = JSON.stringify({ items });JSON.stringify is the correct serialiser for anything that goes back into JSON.parse; string interpolation is where the commas come from.
2. BOM and Windows editors
A UTF-8 BOM is invisible in an editor and fatal to JSON.parse. Files written by PowerShell 5 (Out-File) and some Windows tools add it by default:
file config.json # 'UTF-8 Unicode (with BOM) text'
sed -i '1s/^\xEF\xBB\xBF//' config.jsonIn Node, strip it before parsing; in browsers, await res.text() then strip, instead of res.json() which throws without showing you the byte.
3. response.json() hides the body
await res.json() throws SyntaxError: Unexpected token '<' in JSON at position 0 when the server returned an HTML error page — a 404 or a proxy page. The message is about the first character of the markup, not about JSON at all:
const res = await fetch(url);
const text = await res.text();
if (!res.ok) throw new Error(`${res.status} ${text.slice(0, 200)}`);
const data = JSON.parse(text);Reading the text once also avoids the TypeError: Body is unusable: Body has already been read that follows a res.json() retry in a catch block.
4. NDJSON and streamed responses
A file with one object per line is not a JSON document. Splitting on newlines and parsing each line keeps offsets meaningful:
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
for await (const line of createInterface({ input: createReadStream('events.ndjson') })) {
if (!line.trim()) continue;
const event = JSON.parse(line) as { type: string };
if (event.type === 'error') console.error(line);
}The error Unexpected non-whitespace character after JSON at position N is the tell that you parsed a whole file that contained records.
5. tsconfig.json, .vscode/settings.json and JSONC
These files allow comments and trailing commas by design, and JSON.parse will never read them. Use a JSONC parser, or strip comments before parsing when you only need values:
import { parse } from 'jsonc-parser';
const config = parse(await readFile('tsconfig.json', 'utf8'), [], {
allowTrailingComma: true,
disallowComments: false,
});Do not "fix" tsconfig.json by removing its comments: the tool that reads it supports them, and the next editor will add them back.
6. Type the result, because any is not a type
JSON.parse returns any, so data.user.name compiles and explodes at runtime. Validate at the boundary once, and every consumer gets a real type:
type User = { id: string; name: string; tags: string[] };
function isUser(value: unknown): value is User {
if (typeof value !== 'object' || value === null) return false;
const v = value as Record<string, unknown>;
return typeof v.id === 'string' && typeof v.name === 'string' && Array.isArray(v.tags);
}
const parsed: unknown = JSON.parse(text);
if (!isUser(parsed)) throw new Error('unexpected payload shape');
console.log(parsed.name.toUpperCase()); // typedA reviver can transform values but cannot add types; JSON.parse(text) as User is a cast, not a check.
Common Compilation/Runtime Mistakes & Version Gotchas
JSON.parseon an object. It stringifies to[object Object]and fails at position 0; call it only on a string, andtypeofthe input when the value comes from a cache.JSON.stringifydropping fields.undefinedvalues, functions and symbols disappear, andNaNbecomesnull— a round trip through JSON is not an identity operation, which breakstoEqualtests that includeundefinedkeys.- Prototype pollution through
__proto__.JSON.parse('{"__proto__":{"admin":true}}')creates an own property, but merging that object with a naiveObject.assignsets the prototype. Validate keys before merging untrusted JSON. - Big integers losing precision.
JSON.parse('{"id":12345678901234567890}')rounds because numbers are IEEE-754 doubles. UseJSON.parse(text, (k, v) => ...)carefully, or keep ids as strings at the boundary. - Error messages that changed with V8. Position-based messages differ between Node 18 and Node 20+, so log the whole message plus a snippet rather than matching on
Unexpected token. - Duplicated keys.
{"a":1,"a":2}parses to{a:2}without warning; a generator that emits a key twice produces silent data loss. Dateobjects in a reviver. A reviver runs bottom-up, so a date string converted at a leaf is fine, but reviving a whole object to a class instance before its children are visited is not; convert after parsing instead.
Related tools. Paste a payload into the JSON formatter to see exactly where it stops being valid — the formatter reports the same offset JSON.parse does but shows the surrounding structure; when the difference is between two responses, the text diff tool makes the introduced comma or quote obvious, and escaped strings can be unescaped with the same formatter before they are parsed again.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesZod infer vs TypeScript Interfaces: Runtime Validation Gaps
An interface validates nothing, z.infer is the output type and not the input, and Zod 4 renamed the error helpers. What each one actually guarantees.
TypeScript Decorators: Standard vs experimentalDecorators
TS1240 appears when a legacy decorator meets the stage 3 transform, and the reverse breaks NestJS DI. How the two signatures differ and which flag each stack needs.
TS2307 and TS2835: Cannot Find Module Under moduleResolution NodeNext
NodeNext models Node's real resolution, so .js belongs in the source import and exports maps decide what exists. Why bundler resolution hides both errors.
TypeScript strict Mode: TS2531, TS7006, and TS18047 Migrations
strict is nine flags at once. Count errors per code, fix them in the order that keeps the build green, and narrow instead of asserting.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.