Fix unexpected token errors in JSON

Why parsers report an unexpected token or say text is not valid JSON, how to find the exact cause, and when formatting or auto-repair tools are safe to use.

An 'unexpected token' error means a JSON parser hit a character it cannot accept at that position. Newer versions of JavaScript engines often add that the input 'is not valid JSON' and quote the start of the text. Other engines word it differently, for example 'unexpected character at line 1 column 1'. The message names a symptom, not a cause. This guide covers how to find the cause, which fixes are safe, and when a formatting or repair tool might change your data instead of just tidying it.

Short recommendation

Use a validator and a standard pretty-printer whenever you need to read or debug JSON. A validator changes nothing. A pretty-printer only changes whitespace between tokens, so the data keeps its meaning. Use automatic 'repair' tools with care. They can turn hand-written, nearly-JSON text into valid JSON, but they do it by guessing, and a wrong guess can change your data without any warning. If the broken JSON comes from an API, a file export or another program, fix the producer instead of repairing the output. Keep the original, unformatted bytes when exact content matters: signed or hashed payloads, byte-level diffs, or numbers too large for the parser to hold precisely.

What the error actually tells you

Strict JSON allows only a small set of things. Objects and arrays. Strings in double quotes. Numbers. The literals true, false and null. Whitespace made of space, tab, line feed and carriage return. Anything else outside a string is a syntax error. That includes single quotes, comments, trailing commas, unquoted keys, undefined and NaN. The parser stops at the first character it cannot accept, and the reported token or position points there.

The first unexpected character is usually the strongest clue:

First unexpected character | Likely cause | How to confirm
< at position 0 | You received an HTML page instead of JSON, such as an error page, a login redirect or a 404 | Log the status code, the Content-Type header and the first characters of the raw body
An empty-input message such as 'Unexpected end of JSON input' | The body is empty, or the text was cut off | Check the body length and look for a 204 or empty response
o, or a message quoting "[object Object]" | You passed something that was already a parsed object, so it was converted to a string first | Check typeof on the value before parsing
A message quoting "undefined" | The variable was never set | Trace where the value is assigned
An invisible character at position 0 | A byte order mark (U+FEFF) at the start of a file | Print the code point of the first character
' or a letter where a key should be | JavaScript object syntax rather than JSON: single quotes or unquoted keys | Inspect the text around the reported position
} or ] right after a comma | A trailing comma | Inspect the character just before the bracket
Curly quote characters | Smart quotes, substituted by a word processor, chat app or other editor | Print the code point; straight quotes are U+0022

Treat this table as a starting point, not a diagnosis. The same symptom can have more than one cause. Confirm the cause by looking at the actual text the parser received.

Checks that tell the causes apart

Most of these errors become obvious once you look at the exact text that reached the parser. For HTTP responses, read the body as text first, and only then parse it:

const res = await fetch(url);
const body = await res.text();
console.log(res.status, res.headers.get("content-type"));
console.log(JSON.stringify(body.slice(0, 120)));
const data = JSON.parse(body);

Wrapping the preview in JSON.stringify makes hidden characters visible as escape sequences. That covers a byte order mark, non-breaking spaces and zero-width characters, which would otherwise look like nothing. A status code such as 401, 404 or 500, or a text/html content type, means you are looking at a server or routing problem, not a JSON problem.

If the error gives a position, look at the characters around it and read the code point there:

const pos = 42; // position from the error message
console.log(JSON.stringify(text.slice(Math.max(0, pos - 20), pos + 20)));
console.log("U+" + text.codePointAt(pos).toString(16).toUpperCase().padStart(4, "0"));

The position is counted in UTF-16 code units, not visible characters. An emoji or another character outside the Basic Multilingual Plane counts as two code units, so the reported position may not match the column your editor shows.

Targeted corrections

  • HTML instead of JSON: fix the URL, the authentication or the server error. Before parsing, check res.ok and the content type, and show a readable error message when either is wrong.
  • Empty body: handle the empty response explicitly. Do not pass an empty string to the parser.
  • Already-parsed value: remove the extra parse call. Many HTTP client libraries already return parsed objects.
  • Byte order mark: remove it only when it is the first character, for example with text.replace(/^\uFEFF/, ""). The JSON specification says producers must not add one and allows parsers to ignore it, but JavaScript's built-in parser rejects it.
  • Object-literal syntax: switch to double quotes, quote every key and remove trailing commas. If the input is meant to allow comments or trailing commas, as some config formats do, use a parser for that format instead of strict JSON.
  • Smart quotes and non-breaking spaces: replace them with straight double quotes and ordinary spaces, then turn off automatic quote substitution in the editor that introduced them.

For example, the first line below fails in a strict parser, and the second line is the corrected version:

{ 'name': "Ada", age: 36, }
{ "name": "Ada", "age": 36 }

What formatting and repair tools actually change

Pretty-printing and minifying change only whitespace between tokens. Whitespace inside strings is left alone. Many tools work by parsing the input and then writing it back out, though, and that round trip can introduce other changes:

  • Duplicate keys: the JSON specification only says keys should be unique. JavaScript's parser keeps the last value, so a re-serialized document silently loses the earlier ones.
  • Large numbers: integers beyond 2^53 (9007199254740992) cannot be represented exactly as JavaScript numbers, so a JavaScript-based formatter can change their digits.
  • Key order: JavaScript objects list integer-like keys first, in ascending order. An object with keys "b", "2" and "1" comes back as "1", "2", "b".
  • Escapes: a sequence like \u00e9 may be written back as the literal character é. The meaning is the same, but the bytes differ, which matters for hashes and diffs.

Repair tools go further. They guess at intent: converting quotes, adding missing brackets, dropping comments or truncated content. Always compare a repaired result against the original before you rely on it.

Terms like 'mirror', 'reverse' or 'fancy font' do not describe JSON formatting. However, the output of styled-text or mirror-text generators can end up in JSON. Inside a string, styled Unicode letters such as mathematical bold characters are valid JSON. They are still different characters from plain letters, though, so a key written that way will not match the plain key your code looks up. Outside a string, those characters and bidirectional control characters such as U+202E are syntax errors. Inside a string, bidirectional controls are allowed, but they can make the text display in a different order than it is stored, which makes the JSON misleading to read.

Copying, sharing and readability

Many unexpected-token errors are caused by copying. Rich-text editors, document tools and some messaging apps may replace straight quotes with curly ones or insert non-breaking spaces. Copying from a rendered web page can bring in zero-width characters. To share JSON safely, use a code block or attach the file instead of pasting it as formatted prose. Validate it again after pasting it somewhere new. These risks depend on the app and its settings, so test the specific destination instead of assuming all of them behave the same way.

Indented JSON is easier to scan visually and produces clearer line-based diffs. Minified JSON is smaller, but it is hard to read or review. No scoped testing was available for how screen readers present indented versus minified JSON, so this article makes no claim about that. If accessibility matters for your audience, test it with the assistive technology they actually use.

Online formatters and validators receive whatever you paste into them. This article has no evidence about how any particular tool handles or stores that data, and you cannot judge it from the tool's appearance or marketing. For tokens, personal data or other sensitive payloads, use a local validator, an editor's built-in formatter or a command-line tool instead.

Gaps in this guide

The error wording described here reflects the general behavior of common JavaScript engines, and it varies by engine and version. No specific formatter, validator or repair tool was tested for this article. Check the behavior of the tool you use, especially how it handles large numbers, duplicate keys and key order, against its own documentation or a small test document.