The Frustration of Invalid JSON in Production
Every software engineer, API architect, and DevOps professional has encountered the infamous runtime exception:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)
In modern distributed microservices, JSON (JavaScript Object Notation, formalized by RFC 8259) is the universal data interchange format for REST APIs, GraphQL payloads, AWS Lambda events, and configuration files. Yet despite its apparent simplicity, JSON's strict grammar rules frequently cause painful parsing failures when moving data between backend languages (Python, Go, Java, PHP) and frontend browsers.
In this guide, we break down the most common JSON syntax pitfalls, examine the mathematical grammar enforced by RFC 8259, and demonstrate how to validate, repair, and query complex JSON structures using JSONPath.
You can instantly validate, repair, or inspect nested payloads with our free, 100% private JSON Formatter & Validator.
The Top 5 Most Common JSON Syntax Errors
1. "Unexpected token < in JSON at position 0"
This error almost always occurs when your API client (like fetch or axios) expects a JSON payload from a server, but receives an HTML error page instead (such as a 404 Not Found, 502 Bad Gateway, or 500 Internal Server Error page starting with <!DOCTYPE html>).
Diagnosis: Inspect your HTTP response status code before attempting to parse the body:
const response = await fetch('/api/user'); if (!response.ok) { const errorText = await response.text(); throw new Error(`HTTP ${response.status}: ${errorText.slice(0, 100)}`); } const data = await response.json();
2. Trailing Commas in Objects and Arrays
Unlike JavaScript, Python dictionaries, or modern TypeScript, RFC 8259 JSON strictly forbids trailing commas:
// ❌ INVALID JSON (Causes SyntaxError) { "service": "authentication", "port": 8080, "enabled": true, } // ✅ VALID RFC 8259 JSON { "service": "authentication", "port": 8080, "enabled": true }
3. Single Quotes Instead of Double Quotes
Standard JSON requires double quotes (") for both keys and string values. Single quotes (') or backticks (```) are completely invalid in standard JSON:
// ❌ INVALID JSON { 'userId': 'usr_94829', 'role': 'admin' } // ✅ VALID RFC 8259 JSON { "userId": "usr_94829", "role": "admin" }
4. Unquoted Object Keys
In JavaScript object literals, quotes around property names are optional. In standard JSON, every object key MUST be wrapped in double quotes:
// ❌ INVALID JSON { name: "Server-US-East", datacenter: "us-east-1" } // ✅ VALID RFC 8259 JSON { "name": "Server-US-East", "datacenter": "us-east-1" }
5. Python / Language-Specific Primitives (True, False, None)
When dumping data directly from Python without json.dumps(), developers often paste strings containing capitalized booleans:
| Python Literal | Invalid in JSON | Valid RFC 8259 Equivalent |
|---|---|---|
True | True | true (lowercase) |
False | False | false (lowercase) |
None | None | null (lowercase) |
Our Online JSON Formatter features an intelligent Auto-Repair Engine that automatically fixes single quotes, trailing commas, unquoted keys, and Python literals with a single click.
RFC 8259 Standard vs. JSON5 vs. JSONC
Understanding the differences between standard JSON and its variants helps prevent API integration bugs:
| Feature | Standard JSON (RFC 8259) | JSONC (VS Code Config) | JSON5 (Modern Extension) |
|---|---|---|---|
| Object Keys | Double quotes strictly required | Double quotes strictly required | Unquoted ECMAScript identifiers allowed |
| String Quotes | Double quotes (") only | Double quotes (") only | Single quotes (') and double quotes (") |
| Trailing Commas | ❌ Strictly forbidden | ✅ Allowed | ✅ Allowed in objects & arrays |
| Comments | ❌ Forbidden | ✅ // and /* */ allowed | ✅ // and /* */ allowed |
| Numbers | Standard decimal | Standard decimal | Hex (0x12), leading decimal (.5), Infinity, NaN |
| Multiline Strings | ❌ Requires | ||
| ❌ Requires | |||
| ✅ Escaped newlines allowed |
Extracting Nested Data with JSONPath Expressions
When dealing with massive API payloads (such as AWS CloudTrail logs, Kubernetes resource manifests, or Stripe event webhooks), traversing multi-level structures manually is inefficient. JSONPath provides an XPath-like syntax for querying JSON documents:
{ "store": { "books": [ { "category": "fiction", "title": "Dune", "price": 18.99 }, { "category": "non-fiction", "title": "Sapiens", "price": 14.50 }, { "category": "fiction", "title": "Neuromancer", "price": 12.00 } ], "location": "San Francisco" } }
Essential JSONPath Cheat Sheet:
| JSONPath Syntax | Query Description | Result in Sample Payload |
|---|---|---|
$.store.location | Access direct property | "San Francisco" |
$.store.books[*].title | Extract all book titles | ["Dune", "Sapiens", "Neuromancer"] |
$..price | Recursive descent: find all prices | [18.99, 14.50, 12.00] |
$.store.books[0, 2] | Multiple array indices | First and third book objects |
$.store.books[?(@.price < 15)] | Filter expression (price < 15) | ["Sapiens", "Neuromancer"] |
$.store.books[?(@.category == 'fiction')] | Filter by category | ["Dune", "Neuromancer"] |
Dangerous JSON Edge Cases: 64-Bit Integers & The Unicode BOM
Even valid-looking JSON can trigger silent corruption in production distributed systems:
1. The 64-Bit Integer Precision Bug (Twitter Snowflake IDs)
JavaScript engines parse all numbers as IEEE 754 double-precision floating-point numbers, which have a safe integer limit of Number.MAX_SAFE_INTEGER (2^53 - 1, or 9,007,199,254,740,991):
- Backend databases (PostgreSQL, MySQL) routinely generate 64-bit unsigned integers (
uint64orBIGINT) for primary keys and Snowflake IDs (e.g.,18446744073709551615). - When parsed by browser
JSON.parse(), the last digits are rounded:JSON.parse('{"id": 16123456789012345678}'); // Yields: { id: 16123456789012346000 } ❌ (Silent data corruption!) - Fix: Always serialize 64-bit IDs and high-precision financial decimals as strings (
"id": "16123456789012345678").
2. The Invisible UTF-8 Byte Order Mark (BOM)
When saving JSON files on Windows in Notepad or legacy editors, the editor often prepends an invisible three-byte sequence (0xEF, 0xBB, 0xBF, representing the Unicode Byte Order Mark ).
- Because RFC 8259 forbids leading non-whitespace characters before the initial
{or[, standard parsers throw:SyntaxError: Unexpected token in JSON at position 0. - Strip the BOM using a clean buffer slice or our online validator before deserialization.
Streaming JSON vs. NDJSON for High-Volume Systems & LLMs
Traditional JSON requires the entire document structure to close (} or ]) before any parsing can begin. For multi-gigabyte database exports or real-time streaming LLM responses (OpenAI, Anthropic), Newline Delimited JSON (NDJSON / JSON Lines) is preferred:
| Protocol | Structure Format | Parsing Mechanism | Primary Use Case |
|---|---|---|---|
| Standard JSON | Single root object/array [ {...}, {...} ] | In-memory DOM parsing via JSON.parse() | Standard REST API requests and responses |
| NDJSON (JSONL) | One valid JSON object per line separated by ` | ||
| ` | Line-by-line stream processing | BigQuery exports, Datadog/ELK logs, real-time AI token generation |
Frequently Asked Questions (FAQ)
Is JSON a strict subset of JavaScript?
Historically, no. Prior to ECMAScript 2019 (ES10), JSON allowed unescaped Line Separator (
) and Paragraph Separator (
) characters inside strings, whereas JavaScript string literals threw syntax errors. With the adoption of the "Sub-JSON" proposal in modern JavaScript, all valid JSON strings are now valid JavaScript string literals.
Why does JSON.stringify() delete undefined, Symbol, and functions?
In standard RFC 8259, values can only be strings, numbers, booleans, null, arrays, or objects. When JSON.stringify() encounters undefined, functions, or Symbols within an object, it simply omits the key. Within an array, it converts them into null to preserve array indices.
How do I enforce JSON compliance across my engineering team?
Use JSON Schema (Draft 7 or Draft 2020-12) coupled with automated CI/CD linters (such as ajv or spectral). Validating payloads against strict schema contracts during unit tests prevents schema drift and downstream breaking changes.
Are comments ever permitted in standard JSON?
No. Douglas Crockford intentionally removed comments from the original JSON specification to prevent developers from storing parsing directives inside comments, preserving simplicity and interoperability across languages.
Format, validate, and minify your payloads in real time with our client-side JSON Formatter & Validator.
