JSON Error Library: Common JSON Errors Developers Encounter and How to Fix Them
Most JSON errors are technically simple — a missing comma, an unescaped backslash, a trailing quote. The difficult part is figuring out where the problem actually is.
A missing comma buried inside a 5,000-line API response can waste an entire afternoon. A malformed config file can silently break deployments without clear error messages. An escaped character in the wrong place can make a perfectly normal payload impossible to parse, leaving you staring at cryptic parser output.
After enough debugging sessions, most developers end up building a mental "JSON error library" — a collection of recurring parser errors, what causes them, and the fastest ways to fix them. This guide collects those patterns into a single reference, drawn from real production issues I've encountered across frontend apps, backend APIs, configuration management, and third-party integrations.
Why JSON Errors Are So Common
JSON looks deceptively simple. It's just key-value pairs, arrays, and nested objects. How hard can it be?
But modern applications generate and consume JSON everywhere:
- REST API requests and responses
- GraphQL query results
- Configuration files (
package.json,tsconfig.json) - Environment variables containing serialized JSON
- Frontend state management (Redux, Vuex)
- Application logs
- Webhook payloads from third-party services
- Microservice communication
- Database document storage (MongoDB, CouchDB)
Once payloads become deeply nested or dynamically generated from multiple sources, tiny syntax mistakes become nearly impossible to detect manually. That's why developers rely heavily on tools like JSON Formatter and JSON Validator during debugging workflows.
The reality is that JSON parsers across all languages enforce strict syntax rules. Even a single invalid character breaks parsing completely, and the error messages aren't always helpful.
1. Unexpected Token in JSON
This is probably the most common parser error developers see. It shows up constantly in console logs and error tracking systems.
Example:
JSON.parse("{ name: 'Alex' }")
Error:
Unexpected token n in JSON at position 2
Why It Happens
JSON requires two non-negotiable rules:
- Keys must use double quotes:
"name"notnameor'name' - String values must use double quotes:
"Alex"not'Alex'
This is valid JavaScript:
const user = { name: 'Alex', age: 30 }
But it is not valid JSON.
Correct JSON:
{
"name": "Alex",
"age": 30
}
Real-World Scenario
This error appears constantly when:
- Copying JavaScript objects into JSON files
- Manually editing API mocks for testing
- Building test payloads quickly during development
- Writing documentation examples
- Creating configuration templates
Developers often forget that JavaScript object syntax and JSON syntax are not identical. JavaScript is forgiving — it accepts single quotes, optional quotes around keys, trailing commas. JSON is strict.
I've seen this error countless times during code reviews, especially in teams where frontend developers write mock data by hand. The habit of writing { name: 'test' } in JavaScript carries over into JSON files, causing parse failures.
2. Unexpected End of JSON Input
Example:
JSON.parse('{ "status": "ok" ')
Error:
Unexpected end of JSON input
Why It Happens
The parser reached the end of the string before the JSON structure finished. Typical causes:
- Missing closing brace
}or bracket] - Incomplete API responses (network interruption)
- Interrupted network requests (timeout, connection drop)
- Empty server responses (backend crash)
- Truncated file reads (incomplete file write)
A Very Common Backend Bug
This pattern fails constantly in production environments:
const data = await response.json()
Why? Because the server may return:
- Empty text (no response body)
- HTML error pages (500 Internal Server Error)
- Authentication redirects (302 Found → login page)
- Truncated payloads (request timeout mid-response)
When this happens, response.json() throws immediately without telling you what the server actually sent back. You're left guessing whether it's a syntax error or something else entirely.
How Experienced Developers Debug It
Instead of assuming the response is valid JSON:
const text = await response.text()
console.log('Raw response:', text)
console.log('Content-Type:', response.headers.get('content-type'))
console.log('Status:', response.status)
if (text) {
try {
const data = JSON.parse(text)
// Process data
} catch (err) {
console.error('Failed to parse JSON:', err.message)
console.error('Response preview:', text.substring(0, 200))
}
}
This debugging habit alone solves a surprising number of production issues. You can immediately see if the server returned HTML, an error message, or an incomplete payload. For more details on this specific error pattern, see our guide on JSON parse errors explained.
3. Trailing Comma Errors
Invalid JSON:
{
"debug": true,
"verbose": false,
}
Error:
Unexpected token } in JSON at position 42
JSON does not allow trailing commas. Not in objects, not in arrays.
Why Developers Still Hit This Error
Modern editors (VS Code, WebStorm, Sublime Text) automatically format JavaScript objects with trailing commas for cleaner git diffs. When developers copy those formatted objects into JSON files, the trailing commas accidentally remain.
This becomes especially common in:
- Configuration files (
package.json,.eslintrc.json) - Localization files (i18n JSON with hundreds of keys)
- Mock API payloads for integration testing
- Environment variable JSON strings
- Generated JSON from template engines
I once spent an hour debugging a CI/CD pipeline failure only to discover a trailing comma in a config.json file that had been auto-formatted by Prettier. The pipeline validator was stricter than our local development environment, catching the error only during deployment.
The Fix
Remove the last comma in objects and arrays:
{
"debug": true,
"verbose": false
}
Many formatters automatically remove trailing commas when beautifying JSON, which is another reason to use validation tools during development.
4. Invalid Escape Character
Broken JSON:
{
"path": "C:\new-folder",
"regex": "\d{3}-\d{4}"
}
Error:
Invalid escape character
Why It Happens
Backslashes must be escaped in JSON strings. The parser interprets \n as a newline character, \t as a tab, \r as carriage return, etc. When it encounters \n in C:\new-folder, it tries to interpret it as an escape sequence and fails because \n followed by e is not a valid escape.
Correct version:
{
"path": "C:\\new-folder",
"regex": "\\d{3}-\\d{4}"
}
Real Production Examples
This issue appears frequently with:
- Windows file paths:
C:\Users\Documents\File.txt→C:\\Users\\Documents\\File.txt - Regex patterns:
"\d+"→"\\d+","\w+\s+\w+"→"\\w+\\s+\\w+" - Generated HTML:
<div class=\"test\">needs proper escaping - Serialized Markdown: Backticks, underscores, and special characters
- File system APIs: Paths returned from Node.js
fsmodule - Database queries: SQL strings with escape sequences
Escaping problems become much harder to debug once payloads are nested deeply or generated dynamically. If you're building file system APIs, working with Windows-based backends, or processing regex patterns from user input, this error will find you eventually.
When JSON is generated programmatically using JSON.stringify(), escaping is handled automatically. But when you construct JSON strings manually or through template concatenation, escaping becomes your responsibility.
5. Single Quotes Instead of Double Quotes
Invalid:
{
'name': 'Alex',
'email': 'alex@example.com'
}
Valid:
{
"name": "Alex",
"email": "alex@example.com"
}
Why This Keeps Happening
Because many developers manually write JSON while thinking in JavaScript syntax. JavaScript accepts both single and double quotes for strings (and even template literals), so the habit carries over.
This error is especially common during:
- Quick debugging sessions (typing JSON directly in console)
- Test payload creation in Postman or Insomnia
- API documentation writing (examples in README files)
- Manual config file edits (adding a new setting quickly)
- Chat/Slack sharing of JSON snippets
The fix is simple: always use double quotes for JSON. If you're typing JSON by hand frequently, consider using a formatter that auto-corrects quote styles or validates syntax in real-time.
6. Comments Inside JSON
Invalid:
{
// User information
"name": "Alex",
/* Additional contact details */
"email": "alex@example.com"
}
Error:
Unexpected token / in JSON at position 4
JSON does not support comments. Not single-line (//), not multi-line (/* */).
Why This Causes Confusion
Developers expect JSON to behave like:
- JavaScript: Supports both
//and/* */comments - YAML: Supports
#comments - TypeScript configuration:
tsconfig.jsonsupports comments via JSONC - HJSON or JSONC: Comment-enabled JSON variants used in some tools
But standard JSON (RFC 8259) is intentionally strict. The specification excludes comments to keep the format simple and universally parseable across all languages and platforms.
Some tools allow JSON-like comments internally:
- VS Code's
settings.jsonuses JSONC (JSON with Comments) - Some linters accept comments in configuration files
- Certain frameworks preprocess JSON to strip comments before parsing
This makes the behavior even more confusing across different environments. A JSON file that works in VS Code settings might fail in a strict production parser.
If you need comments in configuration files, consider:
- Using YAML instead (native comment support)
- Adding a separate
.mddocumentation file - Using JSON Schema for field descriptions
- Storing metadata in dedicated comment fields:
"_comment": "User information"
7. Unexpected Token < in JSON
This error is incredibly common in frontend applications consuming APIs. It's one of the first errors junior developers encounter when learning fetch/axios.
Error:
Unexpected token < in JSON at position 0
What It Usually Means
The server returned HTML instead of JSON. Typically, the response starts with:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
The JSON parser sees the < character immediately (position 0) and crashes.
Common Causes
- Authentication redirects: Unauthenticated requests redirected to login page (HTML)
- 404 pages: Invalid API endpoint returns HTML 404 error page
- Server errors: 500 Internal Server Error returns HTML error page with stack trace
- Proxy misconfiguration: Reverse proxy (NGINX, Apache) serving wrong content type
- Incorrect API endpoints: Typo in URL returns HTML landing page instead of API response
- Maintenance pages: Server returning maintenance mode HTML page
How Developers Usually Debug It
Instead of blindly calling:
const data = await response.json()
Inspect the raw response first:
const text = await response.text()
console.log('Response:', text.substring(0, 500))
// Check content type header
const contentType = response.headers.get('content-type')
console.log('Content-Type:', contentType)
if (contentType && contentType.includes('application/json')) {
const data = JSON.parse(text)
// Process data
} else {
console.error('Expected JSON but received:', contentType)
console.error('Response preview:', text.substring(0, 200))
}
That usually reveals the actual issue immediately. I've seen this exact pattern solve production bugs in under five minutes. The key insight is: never assume the response is JSON just because you expect it to be.
JSON Errors in Popular Frameworks
Different frameworks and environments introduce their own JSON-related pitfalls.
React
Very common mistake:
const userData = JSON.parse(props.data)
When props.data is already an object (not a string).
Result:
Unexpected token o in JSON at position 1
Because:
JSON.parse('[object Object]')
is invalid JSON. The object gets converted to the string "[object Object]" before parsing, which obviously isn't valid JSON.
Solution: Always check the type before parsing:
if (typeof props.data === 'string') {
const userData = JSON.parse(props.data)
} else {
const userData = props.data // Already an object
}
Or better yet, ensure your component contract is clear about whether data arrives as JSON strings or parsed objects.
Next.js
Common problems include:
- Undefined serialization: Passing
undefinedtoJSON.stringify()returns the string"undefined", not valid JSON - Malformed API routes: Returning HTML from API routes instead of JSON responses (missing
res.json()) - Invalid environment variables:
.envfiles containing malformed JSON strings - getServerSideProps errors: Returning non-serializable objects (Date, Map, Set)
Example of broken env var:
NEXT_PUBLIC_CONFIG={"debug":true,}
That trailing comma breaks parsing immediately when you call JSON.parse(process.env.NEXT_PUBLIC_CONFIG).
Node.js
Environment variables are a major source of JSON issues. Complex configurations stored as JSON strings in .env files often contain:
- Trailing commas (from manual editing)
- Single quotes (developer习惯)
- Unescaped backslashes (Windows paths)
- Missing quotes around keys
Always validate environment variable JSON before using it:
try {
const config = JSON.parse(process.env.APP_CONFIG)
console.log('Config loaded successfully')
} catch (err) {
console.error('Invalid APP_CONFIG JSON:', err.message)
console.error('Value:', process.env.APP_CONFIG)
process.exit(1) // Fail fast
}
Failing fast prevents subtle bugs later in the application lifecycle.
Practical Debugging Workflow
After debugging JSON issues repeatedly across multiple projects and teams, most experienced developers follow roughly the same process. Here's the workflow I use:
Step 1: Inspect Raw Data
Never trust the parser error alone. The error message tells you where the problem is (position number), but not what the problem actually is.
Inspect the raw payload first:
const text = await response.text()
console.log('Raw response:', text)
Look for:
- HTML tags (
<,>) - Error messages
- Truncated content
- Unexpected characters
Step 2: Format the JSON
Paste the raw payload into a JSON Formatter or JSON Validator. Formatting immediately reveals:
- Broken nesting (mismatched braces/brackets)
- Missing commas between properties
- Malformed arrays
- Escaping issues (unescaped backslashes)
- Trailing commas
For large payloads (1000+ lines), visual inspection is nearly impossible. A formatter highlights the exact line and column where syntax breaks, saving enormous time.
Step 3: Validate Structure
Use strict validation instead of relying on visual inspection. Human eyes miss syntax issues surprisingly often in large payloads, especially when you've been staring at the same JSON for thirty minutes.
Online validators catch:
- Invalid Unicode escape sequences (
\uXXXXwith invalid hex) - Duplicate keys (some parsers allow them, others don't)
- Invalid number formats (leading zeros, NaN, Infinity)
- Boolean/null capitalization errors (
Truevstrue,NULLvsnull)
Step 4: Check Encoding
UTF-8 encoding issues can silently break JSON parsing. This happens especially with:
- Imported CSV files converted to JSON
- Multilingual text (Chinese characters, Arabic script, emoji)
- External APIs with inconsistent encoding headers
- Legacy systems using different character sets (UTF-16, ISO-8859-1)
Invisible characters (BOM markers, zero-width spaces, non-breaking spaces) can cause parsers to fail unexpectedly. If formatting looks correct but parsing still fails, check for hidden characters using a hex editor or specialized tool.
Step 5: Validate Expected Schema
Even valid JSON may still contain incorrect structure. A payload might be syntactically correct but missing required fields, containing unexpected types, or having values outside acceptable ranges.
For larger systems, combine parsing with schema validation libraries:
- Zod: TypeScript-first schema validation with excellent error messages
- AJV: Fast JSON Schema validator, industry standard
- Joi: Powerful object schema description language and validator
Example with Zod:
import { z } from 'zod'
const UserSchema = z.object({
id: z.number(),
name: z.string().min(1),
email: z.string().email(),
age: z.number().optional()
})
try {
const user = UserSchema.parse(JSON.parse(responseText))
// Valid user object with correct types
console.log('User:', user.name)
} catch (err) {
console.error('Schema validation failed:', err.errors)
// Detailed error showing which field failed and why
}
This catches structural issues that pure JSON parsing cannot detect, preventing runtime errors downstream.
Building Your Own JSON Error Reference
One thing experienced developers eventually realize: the same JSON errors repeat constantly across projects, teams, and organizations. Keeping a small internal reference library helps teams debug faster and reduces repeated Stack Overflow searches.
Here's a quick reference table I keep bookmarked:
| Error Message | Common Cause | Quick Fix |
| --- | --- | --- |
| Unexpected token | Invalid syntax (quotes, commas, keys) | Use double quotes, remove trailing commas, quote all keys |
| Unexpected end | Truncated payload, missing } or ] | Check network response, validate completeness, inspect raw text |
| Invalid escape | Broken backslashes in paths/regex | Escape backslashes: \\ instead of \ |
| Unexpected token < | HTML instead of JSON | Check API endpoint, auth status, content-type header |
| Trailing comma | JavaScript object copied to JSON | Remove last comma in objects/arrays |
| Unexpected token o | Parsing already-parsed object | Check type before calling JSON.parse() |
This becomes especially useful in teams working heavily with APIs, microservices, and third-party integrations. Print it, bookmark it, share it with junior developers. For deeper debugging strategies and real-world examples, check out our comprehensive guide on how to fix invalid JSON.
FAQ
What is the most common JSON error?
The most frequent error is Unexpected token, which usually comes from invalid syntax like:
- Using single quotes instead of double quotes (
'key'vs"key") - Leaving trailing commas after the last property
- Forgetting quotes around keys (
namevs"name") - Mixing JavaScript object syntax with JSON
These errors are easy to make when manually writing JSON or copying from JavaScript code. A good formatter catches them instantly.
Why does JSON.parse fail even when the JSON looks correct?
Because tiny syntax issues are easy to miss visually. Common hidden problems include:
- Invalid escaping: Unescaped backslashes in Windows paths or regex patterns
- Invisible characters: BOM markers, zero-width spaces, non-breaking spaces
- Encoding issues: UTF-8 vs UTF-16 mismatches, corrupted characters
- Incomplete payloads: Truncated responses from network timeouts or server crashes
- Mixed content: HTML error pages returned instead of JSON
Always inspect the raw response and use a formatter to highlight syntax issues. What looks correct to human eyes often has subtle problems parsers catch immediately.
Why does JSON require double quotes?
The JSON specification (RFC 8259) strictly requires double quotes for keys and string values. This design choice ensures:
- Consistent parsing across all programming languages and platforms
- Clear distinction from JavaScript (which allows single quotes)
- Simpler parser implementation (one quote type to handle)
- Avoidance of ambiguity with apostrophes in text (
"It's working"vs'It's working')
Single quotes are valid in JavaScript objects but not in JSON. This intentional difference prevents confusion between the two formats.
Why do APIs sometimes return HTML instead of JSON?
Usually because of:
- Authentication failures: Unauthenticated requests redirected to login page (HTML)
- Proxy redirects: Reverse proxy (NGINX, Apache) misconfiguration serving wrong content
- Backend crashes: Server errors (500) returning HTML error pages with stack traces
- Invalid endpoints: Typos in API URLs returning 404 HTML pages
- Wrong content-type: Server sending
text/htmlinstead ofapplication/json - Maintenance mode: Server returning maintenance page HTML
Always check the Content-Type response header and inspect raw responses when debugging API issues. Don't assume the response is JSON just because you expect it to be.
What is the fastest way to debug malformed JSON?
Most experienced developers follow this workflow:
- Inspect raw response: Use
response.text()instead ofresponse.json()to see what the server actually sent - Format the payload: Paste into a JSON formatter to highlight syntax errors and visualize structure
- Validate syntax: Use a strict validator to catch edge cases human eyes miss
- Check escaping: Look for unescaped backslashes, especially in paths and regex patterns
- Verify schema: Use schema validation (Zod, AJV) to check structure beyond syntax
This process usually identifies the issue within minutes, even for large payloads. For quick validation, try our online JSON tools that run entirely in your browser — no data upload, instant results, works offline after first load.
Can JSON contain comments?
No. Standard JSON does not support comments (neither // nor /* */). This is by design to keep the format simple and universally parseable.
Some tools support JSON variants with comments:
- JSONC (JSON with Comments): Used in VS Code settings, Azure configurations
- HJSON (Human JSON): Allows comments, relaxed syntax, multiline strings
- JSON5: Superset of JSON with comments, trailing commas, unquoted keys
But these are not standard JSON and won't work with strict parsers like JSON.parse(). If you need comments in configuration files, consider using YAML (native comment support) or maintaining separate documentation files.
How do I handle large JSON files (10MB+)?
Browser-based formatters may struggle with very large files due to memory limitations. For large JSON files:
- Use command-line tools:
jqhandles files of any size efficiently - Use VS Code: Handles large files better than browsers
- Stream processing: Process JSON in chunks instead of loading entire file
- Specialized tools: Use tools designed for large file performance
If you regularly work with huge JSON files (logs, database exports, API dumps), invest in tools designed for that scale rather than relying on browser-based utilities.
Final Thoughts
JSON itself is simple. Debugging malformed JSON in production systems is not.
Once payloads become large (thousands of lines), deeply nested (ten+ levels), or dynamically generated from external APIs and microservices, parser errors stop being obvious and start becoming workflow problems. That's why experienced developers rely heavily on:
- Formatters: To visualize structure and highlight syntax errors instantly
- Validators: To catch edge cases human eyes miss after hours of debugging
- Raw response inspection: To see what the server actually sent, not what you expected
- Schema validation: To verify structure and types beyond basic syntax
If you regularly work with APIs, configuration files, webhook integrations, or third-party services, having a fast JSON formatter and validator nearby can save an enormous amount of debugging time. The investment in learning these tools pays for itself after the first production incident.
Next time you hit a JSON parse error, resist the urge to stare at the payload for twenty minutes trying to spot the issue manually. Paste it into a formatter, check the raw response, validate the structure, and let the tools do the heavy lifting. You'll debug faster, with less frustration, and with more confidence in your fixes.
Try validating and formatting your JSON directly with our browser-based JSON tools — everything runs locally in your browser, no data leaves your machine, and it's usually faster than switching between multiple editors and online validators. When you're debugging at 2 AM before a deadline, those minutes matter.