JSON formatter/validator · Guide

How to Fix “Unexpected Token” and Other JSON.parse Errors

“Unexpected token in JSON” usually means the parser received something different from the JSON you expected. The cause may be one character in a hand-written payload, but it can also be an HTML error page, an empty API response, incorrect content encoding or a request that reached the wrong endpoint. This guide shows how to identify the real input, locate the failure and fix the source instead of hiding the exception.

What a JSON.parse error actually means

JSON.parse() accepts text and converts a valid JSON value into its JavaScript equivalent. If the text breaks JSON grammar, JavaScript throws a SyntaxError. Browser messages differ: Chrome may report an unexpected token or a position, while Firefox often describes the expected character and gives a line and column. These are different descriptions of the same event—the parser stopped where the input could no longer form valid JSON.

Treat the named token as the point where parsing became impossible, not always as the original mistake. A missing quote near the beginning can make a comma much later look unexpected. Likewise, “Unexpected end of JSON input” says the parser reached the end while it still expected a quote, bracket, brace or value. Inspect a small area before and after the reported position.

First inspect the raw response, not the parsed object

The fastest diagnostic step is to capture the input as text. For a fetch request, temporarily use response.text() and log the status, Content-Type header and the first part of the body. Do not call both text() and json() on the same response because the response body is a stream that is normally consumed once. If needed, clone the response before reading it twice.

Look at the first visible character. A less-than sign usually means the server returned HTML, often a login screen, framework error page, proxy page or 404 document. A leading capital N may be “Not Found”, and an empty string means there was nothing to parse. This explains why fixing punctuation in your JavaScript cannot solve many apparent JSON errors: the bug is in routing, authentication or server output.

Use the position, line and column efficiently

In “Unexpected token } in JSON at position 137”, the position is a zero-based character offset in the string passed to the parser. Print a window around it, for example text.slice(117, 157), rather than scanning a large minified payload. For line-oriented errors, open the raw response in an editor or formatter that shows line and column numbers. Pretty-print only after validation, because a formatter must parse the data before it can safely reindent it.

If the error points to the end, move backward and check the final complete property or array item. Truncated network output, an incomplete file write and string concatenation bugs commonly remove a closing delimiter. Count braces only as a rough clue; braces inside strings do not define structure. A real JSON validator understands strings and escape sequences and therefore gives a more reliable location.

Fix trailing commas, quotes and property names

JSON is stricter than a JavaScript object literal. Object property names and string values require double quotes. Single quotes are not JSON, unquoted keys are not JSON, and a comma after the last property or array element is not allowed. For example, {"name":"Ada",} fails because of the final comma, while {name:"Ada"} fails because the key is not quoted.

Do not repair arbitrary API output with broad regular expressions that replace every quote or delete every comma before a brace. Such replacements can corrupt valid characters inside strings. Correct the serializer or source data instead. On a server, build an object or native data structure and use the platform JSON encoder; do not assemble JSON by joining strings.

Check strings, escapes, numbers and unsupported values

Inside a JSON string, quotation marks and backslashes must be escaped. A literal newline or tab cannot appear unescaped; use \n or \t. A backslash must begin a supported escape such as \”, \\, \/, \b, \f, \n, \r, \t or \u followed by four hexadecimal digits. Paths copied from Windows and multi-line text are frequent sources of bad escape errors.

JSON numbers cannot have a leading plus sign, leading zeros such as 01, a trailing decimal point or values such as NaN and Infinity. JSON also has no undefined value, comments, functions or dates. Encode missing data as null or omit the property, and encode dates as agreed strings. Valid literal names are lowercase true, false and null.

Why APIs return HTML, empty text or truncated JSON

When the first token is “<”, verify the request URL, HTTP status and redirects. A single-page application may return index.html for an unknown API route. An expired session may redirect to an HTML sign-in form. A reverse proxy can produce its own gateway page before your application runs. Requesting /api/users from the wrong host or missing an Accept: application/json header can select an HTML representation.

Empty bodies are legitimate for some responses, especially 204 No Content, and may also appear after a 304 or a HEAD request. Do not run JSON.parse on an empty string. Truncated JSON can indicate a server exception during streaming, an interrupted connection or a proxy limit. Check server and proxy logs when the body ends halfway through a string or collection.

A safer fetch pattern for JSON APIs

Check response.ok before trusting the body and inspect Content-Type before deciding how to parse it. A robust client reads the text once, handles an empty body explicitly and then parses inside try/catch. When parsing fails, record the URL, status, content type and a short sanitized preview. Never log access tokens, personal data or the entire confidential payload just to diagnose one character.

Content-Type is evidence, not proof. A server can label HTML as application/json or send valid JSON as text/plain. Your client should report a clear contract error in either case. For expected no-content operations, return null or a domain-specific result. For all other success responses, require valid JSON and let monitoring expose a broken backend contract quickly.

Validate the contract and prevent the error from returning

Syntax validation only proves that the text is JSON. It does not prove that user.id exists, that price is a number or that status contains an allowed value. After parsing, validate important API responses with a schema or explicit runtime checks. This turns a vague failure later in the interface into a precise message at the network boundary.

Add tests for successful JSON, structured error JSON, authentication redirects, 204 responses and malformed or truncated bodies. On the server, use one error format across controllers and middleware, set the correct status and Content-Type, and ensure uncaught exceptions are converted to JSON for API routes. These measures prevent the most common “Unexpected token” regressions.

Quick troubleshooting checklist

Confirm the exact request URL and method; inspect status, redirects and Content-Type; read the raw body once; check its first character and its ending; use the reported position as a search window; then validate the payload. If it is HTML or empty, debug the endpoint. If it is almost JSON, fix the producer, serializer or source record.

Before closing the issue, test the failure path as well as the successful path. A JSON API is reliable only when errors, expired authentication and empty results follow a documented contract. The goal is not merely to silence JSON.parse—it is to make the client and server agree about every response.

Frequently asked questions

What causes “Unexpected token < in JSON at position 0”?

The response usually starts with HTML rather than JSON. Check the URL, status, redirects, authentication and raw response body; common sources are 404 pages, login screens and proxy errors.

How do I fix “Unexpected end of JSON input”?

Check for an empty or truncated body and for missing closing quotes, brackets or braces. Do not parse a legitimate 204 response, and inspect server logs if output stops partway through.

Can JSON use single quotes or trailing commas?

No. JSON strings and property names use double quotes, and the final member of an object or array cannot have a trailing comma.

Should I wrap every JSON.parse call in try/catch?

Catch parsing at untrusted boundaries so you can return a useful error, but also validate status and content type. A catch block should not silently replace broken data with an empty object.

Is valid JSON automatically a valid API response?

No. Syntax validation says only that parsing is possible. Validate the resulting fields, types and allowed values against the API contract.

Ready to try it?

Open the free browser-based JSON formatter/validator and apply what you just read — no sign-up, runs locally.

Open the JSON formatter/validator tool