How to Fix Invalid JSON: Common Errors and Solutions
Learn how to diagnose and fix invalid JSON, understand parser error messages, avoid syntax pitfalls like trailing commas and single quotes, and ensure RFC 8259 compliance.
When a JSON parser throws an error like SyntaxError: Unexpected token in JSON at position 142 or json.decoder.JSONDecodeError, it stops your application immediately. APIs reject requests, background workers crash, and configuration files fail to load. Fixing invalid JSON requires identifying the exact character where the parser stopped and bringing the text into conformance with the strict JSON grammar defined by RFC 8259.
In most cases, invalid JSON results from one of five syntax issues: trailing commas after array or object elements, single quotes instead of double quotes, unquoted keys, unescaped backslashes, or misplaced brackets.
You can test and inspect any payload immediately using ToolPorta's JSON Validator to highlight syntax errors right in your browser. This guide explains why JSON parsers reject payloads, provides a repeatable 4-step diagnostic workflow, covers practical code fixes for every major syntax error, compares JSON to looser alternatives like JSON5, and outlines safe debugging practices.
What makes JSON invalid (and why parsers fail)#
JavaScript Object Notation (JSON) is not JavaScript code. Although JSON originated as a subset of JavaScript's object literal notation, it is an independent, language-agnostic data interchange format standardized under RFC 8259 and ECMA-404.
Standard JSON parsers operate as strict state machines or recursive descent parsers. They do not guess developer intent or execute lenient fallbacks. If a single comma is misplaced or an apostrophe is used instead of a double quotation mark, the parser encounters a transition it cannot resolve and terminates with a syntax error.
Under the JSON specification, a valid document consists of a single root value. That value must be one of six data types:
- Object: An unordered collection of zero or more comma-delimited key-value pairs wrapped in curly braces (
{}). Keys must be strings enclosed in double quotes ("). - Array: An ordered collection of zero or more comma-delimited values wrapped in square brackets (
[]). - String: A sequence of Unicode characters enclosed strictly in double quotation marks (
"). Control characters and backslashes must be escaped. - Number: A decimal number without leading zeros (unless zero itself), octal notation, or trailing decimal points.
- Boolean: Literal lowercase
trueorfalse. - Null: Literal lowercase
null.
Anything outside this list—such as undefined, NaN, Infinity, functions, single quotes, comments, or trailing commas—is syntactically invalid JSON.
How to diagnose and fix invalid JSON step by step#
When debugging an invalid JSON payload, follow this structured four-step troubleshooting workflow:
- Inspect the parser error message and position offset: Parsers usually output a character position (e.g.,
position 487) or a line-and-column number. In character-offset errors, divide the position by your editor's average line length or paste the payload into an editor that provides direct character offsets. - Check the line immediately preceding the reported error: Parsers frequently encounter a problem on the line after the mistake. For example, if you forgot a comma at the end of line 12, the parser will not report an error until it reads the first token of line 13.
- Isolate syntax errors in a dedicated validator: Paste the payload into the JSON Validator. The validator runs native client-side parsing with contextual error highlighting, indicating both the failing token and expected structural markers.
- Format and inspect the resolved payload: Once the syntax error is corrected, pass the text through the JSON Formatter to verify nesting depth, bracket balance, and data alignment.
Realistic diagnostic example#
Consider an API configuration payload exported from an internal reporting tool. When sent to a server, the request fails with SyntaxError: Expected double-quoted property name at line 5 column 3:
This single snippet contains four distinct syntax violations:
- Line 2 uses single quotes around
'service'. - Line 7 contains a trailing comma after the last array item.
- Line 9 has an unquoted property key (
logLevel). - Line 10 contains unescaped backslashes in a Windows file path (
C:\data\logs).
Here is the fully compliant, corrected JSON:
Common errors and how to fix them#
Most invalid JSON payloads stem from a handful of syntax violations. Recognizing these patterns helps you diagnose parse failures within seconds.
1. Trailing commas in objects and arrays#
JavaScript, Python dictionaries, and modern ECMAScript allow trailing commas after the final element. In standard JSON, a comma acts strictly as a separator between two existing items, not a line terminator. Placing a comma after the final property or array value causes an immediate parse failure.
2. Single quotes instead of double quotes#
In many programming languages, single quotes (') and double quotes (") are interchangeable for strings. In standard JSON, single quotes are illegal for both object keys and string values.
If your string contains a literal double quote, escape it with a backslash (\"):
3. Unquoted object keys#
JavaScript object literals permit identifier names without quotation marks (e.g., { name: "Ada" }). JSON requires double quotation marks around every object key without exception.
4. Unescaped backslashes and file paths#
The backslash (\) is the escape prefix in JSON. If you represent Windows file paths, regular expressions, or network shares, raw backslashes will either trigger an "invalid escape sequence" error or inadvertently escape the next character.
Valid JSON escape sequences are limited to \", \\, \/, \b, \f, \n, \r, \t, and Unicode hex sequences like \u00A9. Any other character preceded by a single backslash is illegal.
5. Comments in JSON files#
Configuration files often tempt developers to write explanatory notes or temporarily disable fields with // or /* */. RFC 8259 explicitly prohibits comments so that parsers remain simple and interoperable across programming languages.
6. Unsupported data types: NaN, Infinity, and undefined#
Standard JSON does not support non-finite numbers or JavaScript's undefined type. When serialized with tools like JSON.stringify(), undefined keys are dropped entirely, while NaN and Infinity are converted to null.
7. "Unexpected token < in JSON at position 0"#
One of the most frequent errors reported in web applications is Unexpected token < in JSON at position 0. This error does not mean your JSON file has a minor typo. It means the payload received by your application is HTML or XML, not JSON.
The character < is the opening bracket of an HTML tag such as <!DOCTYPE html> or <html>. This happens when:
- An API endpoint returns an HTML 404 Not Found or 500 Internal Server Error page.
- A proxy or firewall returns an HTML authentication or captive portal page.
- The request URL or base route is configured incorrectly.
Before attempting to debug the JSON syntax, log the raw HTTP response status code and response body text to confirm what the server actually returned.
Standard JSON vs JSON5 vs JavaScript object literals#
Many developers encounter JSON errors because they confuse standard JSON with relaxed formats like JSON5 or JavaScript object notation. Understanding their differences clarifies why standard JSON parsers reject familiar syntax:
| Syntax Feature | Standard JSON (RFC 8259) | JSON5 | JavaScript Object Literal |
|---|---|---|---|
| Object Key Quotes | Double quotes required ("key") | Optional for valid identifiers | Optional for valid identifiers |
| String Delimiters | Double quotes only ("...") | Single or double quotes | Single, double quotes, or backticks |
| Trailing Commas | Forbidden in objects and arrays | Permitted | Permitted |
| Comments | Forbidden | Line (//) and block (/* */) | Line (//) and block (/* */) |
| Escaped Line Breaks | Forbidden (raw newlines invalid) | Permitted (escaped line break) | Permitted |
| Hexadecimal Numbers | Forbidden (0xFF is invalid) | Permitted (0x10, 0xFF) | Permitted |
| Leading/Trailing Decimals | Forbidden (.5 or 5. invalid) | Permitted | Permitted |
| Special Numerics | Forbidden (NaN, Infinity) | Permitted (NaN, Infinity) | Permitted |
| Native Browser Parser | JSON.parse() | Requires external library | Evaluated by JavaScript engine |
While JSON5 is convenient for local developer tooling (like tsconfig.json or ESLint configurations), standard RFC 8259 JSON remains the universal lingua franca for public REST APIs, webhooks, and cross-platform communication.
When to use a validator vs formatter vs programmatic parsing#
Different phases of software development require different JSON utilities:
| Scenario | Recommended Approach | Key Benefit |
|---|---|---|
| Diagnosing a broken payload or locating a syntax error | JSON Validator | Pinpoints line, column, and unexpected tokens instantly |
| Reviewing nested structures, diffs, or API responses | JSON Formatter | Adds consistent indentation and visual hierarchy |
| Preparing validated data for network transmission | JSON Minifier | Strips unnecessary whitespace to decrease transfer size |
| Validating user input automatically in an application | Language-native parser | Enforces validation in automated test suites and runtime APIs |
If you need to implement programmatic validation within your own codebase, check our dedicated implementation guides:
- Validate JSON in JavaScript and Node.js using
try...catchand nativeJSON.parse(). - Validate JSON in Python using Python's standard
jsonmodule andjson.loads().
Security, privacy, and technical limitations#
When validating JSON data online, security and environment constraints must be considered.
Client-side processing and privacy#
ToolPorta performs JSON validation locally inside your browser using JavaScript and standard browser APIs. The data you paste into the editor is evaluated within your local browser session and is not sent to an application server for analysis.
However, local execution does not replace security hygiene. Avoid pasting unredacted credentials, API private keys, session tokens, or sensitive customer records into any browser window on unmanaged or shared workstations. If you need to debug a production payload, replace sensitive tokens and personally identifiable information (PII) with synthetic placeholder data first.
Performance limits with large datasets#
Standard browser tabs operate within strict memory and thread constraints (typically managed by the browser engine's heap limit). While client-side validators easily process payloads of several megabytes, files exceeding tens or hundreds of megabytes can cause browser tab slowdowns or memory exhaustion. For multi-gigabyte database exports or streaming data pipelines, use command-line stream parsers such as jq or streaming parsers like Python's ijson.
Frequently asked questions#
Why doesn't standard JSON support comments?#
Douglas Crockford intentionally excluded comments from the JSON specification to prevent developers from adding parsing directives, schema hints, or environment flags. Omitting comments ensures that all compliant JSON parsers interpret the exact same data without dialects or interoperability conflicts.
How do I fix "Unexpected token < in JSON at position 0"?#
This error occurs when an application attempts to parse an HTML document as JSON. Inspect the raw network response from your API. You will likely find an HTTP 401 Unauthorized, 404 Not Found, or 500 Internal Server Error returning an HTML error page instead of a JSON payload.
Can JSON represent 64-bit integers accurately?#
JavaScript numbers conform to IEEE 754 double-precision floating-point format, which reliably represents integers up to $2^{53} - 1$ (Number.MAX_SAFE_INTEGER, or 9,007,199,254,740,991). When working with 64-bit database identifiers or high-precision financial values, pass the numbers as double-quoted strings (e.g., "id": "9007199254740993") to prevent rounding errors during parsing.
Why does my JSON fail validation even though it looks correct?#
Invisible characters and formatting artifacts often cause unexplained parse failures. Copying text from word processors, chat apps, or email clients can introduce "smart quotes" (“ and ” instead of "), non-breaking spaces (\u00A0), zero-width spaces (\u200B), or a UTF-8 Byte Order Mark (BOM). Running the payload through a strict validator strips or highlights these hidden characters.
Can an automated tool fix all JSON syntax errors?#
Automated repair tools can safely resolve unambiguous mistakes, such as removing trailing commas, converting single quotes to double quotes, or escaping standard control characters. However, when brackets or braces are missing, an automated tool cannot infer where an object or array was meant to end. Structural ambiguities always require human verification.
Try the related ToolPorta tools#
When you encounter a malformed payload, begin with the JSON Validator to isolate the exact line and character causing the parse failure. Once the errors are resolved, use the JSON Formatter to organize your data into clean, readable structures, or apply the JSON Minifier to produce a lightweight payload for production APIs.