Common JSON Errors: How to Fix SyntaxError, Trailing Commas, and Unquoted Keys
A comprehensive developer guide to diagnosing and fixing the most frustrating JSON errors: unexpected tokens, trailing commas, unquoted keys, and number precision loss.
1. Understanding JSON Parsing Errors in Modern Applications
JavaScript Object Notation (standardized under RFC 8259 and ECMA-404) is the ubiquitous backbone of web APIs, configuration files, and state serialization. Despite its visual resemblance to JavaScript object literals, JSON enforces a significantly stricter grammar. When a client application or server encounters invalid JSON, native parsers (such as V8's JSON.parse() or Python's json.loads()) instantly throw fatal syntax exceptions.
In client-side Single Page Applications (SPAs) and microservice communication, an unhandled JSON parsing exception frequently causes white-screen crashes, failed API handshakes, or silent data dropouts. Understanding the exact mechanics of these errors and how to prevent them is critical for any software engineer building reliable web software.
2. SyntaxError: Unexpected Token in JSON at Position X
The infamous 'SyntaxError: Unexpected token < in JSON at position 0' is one of the most common exceptions in web development. In 95% of cases, this error does not mean your JSON has a minor typo—it means your application received an HTML error page (such as a 404 Not Found, 502 Bad Gateway, or Cloudflare challenge) instead of the expected application/json response body.
```javascript // Dangerous pattern: assuming the response is always JSON const response = await fetch('/api/user/profile'); const data = await response.json(); // Throws if server returns HTML 500 error!
// Safe production pattern const response = await fetch('/api/user/profile'); if (!response.ok) { const errorText = await response.text(); throw new Error(`API error HTTP ${response.status}: ${errorText.slice(0, 100)}`); } const data = await response.json(); ```
When the unexpected token appears at an arbitrary position (like position 42), check for unescaped control characters (such as raw unescaped newlines within a string) or unquoted values.
3. Trailing Commas in Objects and Arrays
JavaScript object literals natively allow trailing commas after the final key-value pair, and ECMAScript specifications actively encourage them to make git diffs cleaner. However, RFC 8259 strictly forbids trailing commas in JSON arrays and objects.
```json // INVALID JSON (Will throw SyntaxError: Expected property name or '}') { "name": "Alice", "role": "Admin", }
// VALID JSON { "name": "Alice", "role": "Admin" } ```
- Never leave a comma after the last item of an array: ["apple", "banana",] will crash standard parsers.
- In automated CI/CD pipelines, use linters like Prettier or WebUtil's JSON Formatter to strip trailing commas prior to deployment.
4. Single Quotes vs Double Quotes and Unquoted Keys
Another frequent mistake made by JavaScript and Python developers is using single quotes (') or backticks (`) for strings or leaving object keys unquoted.
- In JSON, all keys MUST be enclosed in double quotes: {"userId": 101} is valid, whereas {userId: 101} or {'userId': 101} is invalid syntax.
- All string values MUST use double quotes ("). Single quotes are treated as illegal tokens.
- To include a double quote inside a string, escape it with a backslash: "quote": "He said, \"Hello\"".
- To include a backslash, escape it with a double backslash: "path": "C:\\Users\\AppData".
5. Number Precision Loss Beyond 2^53 - 1 (The BigInt Problem)
JSON specification defines numbers as arbitrary decimal values, but most language runtimes parse numbers into IEEE 754 64-bit double-precision floating-point numbers. In JavaScript, the maximum safe integer is Number.MAX_SAFE_INTEGER (9,007,199,254,740,991 or 2^53 - 1).
// Danger: BigInt IDs lose precision in standard JSON.parse
const raw = '{"orderId": 9007199254740995}';
const parsed = JSON.parse(raw);
console.log(parsed.orderId); // 9007199254740996 (CORRUPTED!)
If your backend uses 64-bit database identifiers (such as Twitter snowflake IDs, Stripe transaction IDs, or PostgreSQL BIGINT), always serialize them as strings in your JSON payloads: {"orderId": "9007199254740995"}.
6. Safe JSON Parsing Pattern in TypeScript
To prevent uncaught runtime exceptions from crashing your web app, implement a bulletproof safe parsing utility that returns a typed result object or fallback:
```typescript type Result<T> = { success: true; data: T } | { success: false; error: Error };
function safeJsonParse<T>(jsonString: string): Result<T> { try { const data = JSON.parse(jsonString) as T; return { success: true, data }; } catch (err) { return { success: false, error: err instanceof Error ? err : new Error('Malformed JSON syntax'), }; } }
// Usage const res = safeJsonParse<{ theme: string }>(localStorage.getItem('settings') || ''); if (res.success) { console.log(res.data.theme); } else { console.warn('Fallback to default theme due to corrupt storage'); } ```
For production form handling and API validation, combine safe parsing with runtime schema validation libraries like Zod to ensure the parsed JSON matches your expected TypeScript interfaces.
7. Automated Validation with WebUtil's JSON Formatter
Whenever you encounter a cryptic JSON syntax error in an API payload or configuration file, paste the snippet into WebUtil's JSON Formatter. The tool highlights the exact line and character column where the syntax violates RFC 8259, provides 1-click beautification and minification, and processes everything 100% locally in your browser memory so your sensitive data never leaves your device.
Recommended Articles & Guides
How to Format JSON Properly: A Complete Guide
Learn how to format JSON data correctly with best practices, common patterns, and troubleshooting tips for developers.
URL Encoding and Decoding: What Every Developer Should Know
Understand how URL encoding works, why it matters for web development, and how to properly encode and decode URLs.
Base64 Encoding: Methods, Use Cases, and Best Practices
A deep dive into Base64 encoding, when to use it, common pitfalls, and how it works under the hood.