Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readTypeScript
#JavaScript#TypeScript#JSON#Debugging
3D illustration of brace blocks with a stray amber comma wedged in and a clean bracket beside it

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:

ts
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 JSON

The V8 version decides the wording, which matters when you grep logs for the message:

code
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 7

A runnable diagnostic that names the offending character instead of guessing:

ts
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:

InputMessage fragmentRule
{"a":1,}Expected double-quoted property nameNo trailing commas
{'a':1}Expected property name or }Keys and strings need double quotes
{a:1}Expected property name or }Unquoted keys
// noteUnexpected 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 JSONExactly one top-level value
"line\nbreak"Bad control character in string literalNewlines must be escaped
{"a":"\x41"}Bad escaped characterNo \x, no \', no \v

Parsers and what they accept:

ParserAcceptsReturnsUse for
JSON.parseStrict RFC 8259anyEverything you control
json5 / JSON5.parseComments, trailing commas, single quotesobjectHand-edited config
jsonc-parserComments, trailing commas, preserves errorsAST / valuetsconfig.json, VS Code files
ndjson / split('\n')One value per linestream of objectsLog and export files
JSON.parse + strip-json-commentsComments onlyanyLegacy config files
eval / new FunctionAlmost all JavaScriptvalueNever 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:

ts
// 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:

bash
file config.json # 'UTF-8 Unicode (with BOM) text' sed -i '1s/^\xEF\xBB\xBF//' config.json

In 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:

ts
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:

ts
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:

ts
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:

ts
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()); // typed

A 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.parse on an object. It stringifies to [object Object] and fails at position 0; call it only on a string, and typeof the input when the value comes from a cache.
  • JSON.stringify dropping fields. undefined values, functions and symbols disappear, and NaN becomes null — a round trip through JSON is not an identity operation, which breaks toEqual tests that include undefined keys.
  • Prototype pollution through __proto__. JSON.parse('{"__proto__":{"admin":true}}') creates an own property, but merging that object with a naive Object.assign sets the prototype. Validate keys before merging untrusted JSON.
  • Big integers losing precision. JSON.parse('{"id":12345678901234567890}') rounds because numbers are IEEE-754 doubles. Use JSON.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.
  • Date objects 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.