Common JSON Errors and How to Fix Them (2026 Guide)
If your JSON fails to parse, it’s almost always one of a few fixable syntax issues: quotes, commas, escaping, or invalid values like NaN. This guide shows the exact errors you’ll see, why they happen, and the fastest way to fix them—backed by practical examples and cross-language tips.
Pro tip: Validate as you type with a JSON formatter/validator. Try ZenixTools (https://www.zenixtools.com/) to instantly format, highlight errors, and copy a fixed version.
Key Takeaways (Featured Snippet)
- JSON is strict: double quotes only for keys and strings; no comments; no trailing commas.
- Common failures: trailing comma, single quotes, unescaped characters/newlines, missing commas, invalid numbers, NaN/Infinity/undefined, duplicate keys, mismatched braces, BOM/encoding, or parsing HTML instead of JSON.
- Fast fix workflow: validate → jump to the error index → inspect 5 chars around it → fix quotes/commas/escapes → re-validate.
- Store big integers as strings to avoid precision loss.
- Use JSON Schema to prevent valid-but-wrong data.
Table of Contents
What JSON Really Requires (Quick Primer)
JSON is a text format defined by RFC 8259 and ECMA‑404. It supports:
- Objects: { "key": value }
- Arrays: [ value, value ]
- Strings: double‑quoted only
- Numbers: standard decimal/exp notation (no leading zeros except 0, no + sign)
- Literals: true, false, null
Not allowed: comments, single quotes, trailing commas, undefined/NaN/Infinity, raw control characters, or JavaScript-only syntax.
30‑Second Debug Workflow
- Validate the JSON with a formatter/validator (ZenixTools: https://www.zenixtools.com/).
- Read the error index or line/column. Jump to it in your editor.
- Inspect the 5 characters before and after the index.
- Look for the Big Four: quotes, commas, escaping, invalid values.
- If it came from an API, log the raw response as text first to ensure it’s actually JSON.
The 18 Most Common JSON Errors (with fixes)
1) Trailing comma
- Error examples:
- JavaScript: Unexpected token ] or } in JSON at position ...
- Python: Expecting property name enclosed in double quotes
- Cause: JSON forbids a comma after the last item in an object or array.
- Fix: Remove the final comma.
Invalid:
{
"name": "John",
"age": 30,
}
Valid:
{
"name": "John",
"age": 30
}
2) Unquoted or single‑quoted keys
- Error: Unexpected token a in JSON at position ... or Expecting property name enclosed in double quotes
- Cause: Keys must be double‑quoted strings.
- Fix: Wrap all keys in double quotes.
Invalid:
{
name: 'John'
}
Valid:
{
"name": "John"
}
3) Single quotes for strings
- Error: Unexpected token ' in JSON at position ...
- Cause: Strings must use double quotes.
- Fix: Replace single quotes with double quotes.
Invalid:
{
"name": 'John'
}
Valid:
{
"name": "John"
}
4) Unescaped characters (quotes, backslashes, newlines)
- Error: Unexpected token ... in JSON; invalid string escape
- Cause: Special characters in strings must be escaped.
- Fix: Escape quotes ("), backslashes (\), and control characters (\n, \t, etc.).
Invalid (unescaped quotes inside a string):
{
"quote": "He said, "Hello!""
}
Valid:
{
"quote": "He said, \"Hello!\""
}
Another valid example (newline):
{
"message": "Line one\nLine two"
}
Tip: Use \uXXXX for explicit Unicode escaping when needed, e.g., "\u263A".
5) Missing commas
- Error: Unexpected string (or number) in JSON at position ...
- Cause: Items in objects or arrays must be comma‑separated.
- Fix: Add commas between key/value pairs or array items.
Invalid:
{
"name": "John"
"age": 30
}
Valid:
{
"name": "John",
"age": 30
}
6) Comments are not allowed
- Error: Unexpected token / in JSON at position ...
- Cause: JSON does not support // or /* */ comments.
- Fix: Remove comments before parsing.
Invalid:
{
"name": "John" // user's first name
}
Valid:
{
"name": "John"
}
Workaround: If you need comments while editing, use JSONC/JSON5 in your editor and strip comments before shipping (ZenixTools can convert JSONC → JSON).
7) NaN, Infinity, undefined
- Error: Unexpected token N or u in JSON at position ...
- Cause: These JavaScript values aren’t valid JSON.
- Fix: Use null or explicit strings/numbers.
Invalid:
{
"value": NaN,
"max": Infinity,
"missing": undefined
}
Valid (neutral):
{
"value": null,
"max": null,
"missing": null
}
Valid (preserve meaning as strings):
{
"value": "NaN",
"max": "Infinity",
"missing": "undefined"
}
8) Numbers with leading zeros
- Error: Unexpected number in JSON at position ...
- Cause: Leading zeros aren’t allowed (09, 01, 00 unless the number is exactly 0).
- Fix: Remove leading zeros or quote as a string when needed.
Invalid:
{
"month": 09
}
Valid:
{
"month": 9
}
Or preserve formatting (IDs, codes):
{
"code": "09"
}
9) Duplicate keys
- Symptom: Some parsers accept them (last one wins). Others reject or keep only the last value.
- Cause: The spec doesn’t forbid duplicate names, but behavior is ambiguous and unsafe.
- Fix: Ensure keys are unique.
Problematic:
{
"id": 1,
"id": 2
}
Recommended:
{
"id": 2
}
Tip: If you need multiple values for one concept, use an array: { "id": [1, 2] }.
10) HTML instead of JSON
- Error: Unexpected token < in JSON at position 0
- Cause: You’re parsing HTML (often an error page) as JSON.
- Fix: Inspect the actual response body and headers. Confirm Content‑Type and endpoint.
Quick check in JavaScript:
fetch('/api/data')
.then(r => r.text())
.then(t => {
console.log(t.slice(0, 200)); // Is it HTML?
const data = JSON.parse(t); // Only parse if it's JSON
});
Also confirm HTTP codes: a 403/500 page is often HTML.
11) BOM / encoding issues
- Error: Unexpected token \uFEFF in JSON at position 0
- Cause: A UTF‑8 BOM adds a hidden character at the start of the file.
- Fix: Save files as UTF‑8 without BOM or strip it before parsing.
Strip BOM in JavaScript:
const sanitized = raw.replace(/^\uFEFF/, '');
const data = JSON.parse(sanitized);
12) Large integers lose precision
- Symptom: Big numbers change value after parsing (e.g., long IDs become rounded).
- Cause: JavaScript numbers are IEEE‑754 doubles (53‑bit integer precision). Similar pitfalls exist in other languages if mapped to 64‑bit floats.
- Fix:
- Store big integers as strings in JSON.
- Use a BigInt/BigInteger‑aware parser or post‑processing.
Example (safe):
{
"orderId": "9007199254740993"
}
JavaScript reviver example:
const data = JSON.parse(json, (k, v) => {
return typeof v === 'string' && /^\d{16,}$/.test(v) ? BigInt(v) : v;
});
13) Mismatched brackets/braces
- Error: Unexpected end of JSON input
- Cause: Missing a closing } or ] or adding one too many.
- Fix: Balance brackets/braces; pretty‑print to spot gaps.
Invalid:
{
"users": [
{ "id": 1, "name": "Ava" },
{ "id": 2, "name": "Ben" }
Valid:
{
"users": [
{ "id": 1, "name": "Ava" },
{ "id": 2, "name": "Ben" }
]
}
14) Escaping backslashes (Windows paths, regex)
- Symptom: Paths or regex look truncated or invalid.
- Cause: Backslash is an escape character; a single backslash starts an escape.
- Fix: Double each backslash.
Correct:
{
"path": "C:\\Users\\John\\file.txt",
"regex": "^\\d{3}-\\d{2}-\\d{4}$"
}
15) Multiple JSON values / extra data
- Errors:
- Python: Extra data: line 1 column ...
- Go: invalid character ... after top‑level value
- Cause: Concatenated JSON values without a container or NDJSON confusion.
- Fix: Wrap multiple items in an array, or emit newline‑delimited JSON (NDJSON) and process line by line.
Invalid (two objects stuck together):
{ "a": 1 }{ "b": 2 }
Valid (array):
[ { "a": 1 }, { "b": 2 } ]
NDJSON (each line a separate JSON value):
{"a":1}
{"b":2}
16) Invalid number formats (plus signs, trailing dots, leading dots)
- Errors: invalid number, Unexpected token + or .
- Cause: JSON numbers cannot have a + sign, cannot be like 1. or .5. Exponent notation must be complete (e.g., 1e-3 is fine; 1e is not).
- Fix: Use valid decimal or exponent forms.
Invalid → Valid:
{ "a": +5 } // invalid → { "a": 5 }
{ "b": 1. } // invalid → { "b": 1.0 }
{ "c": .5 } // invalid → { "c": 0.5 }
{ "d": 1e } // invalid → { "d": 1e0 }
17) Unescaped control characters and raw newlines
- Error: Invalid control character at position ...
- Cause: Control chars U+0000–U+001F (including raw newline, tab, carriage return) must be escaped in strings.
- Fix: Replace raw control characters with escapes: \n, \t, \r.
Invalid:
{"msg": "Hello
World"}
Valid:
{ "msg": "Hello\nWorld" }
18) Wrong Content‑Type or charset
- Symptom: Valid JSON body, but client won’t parse automatically.
- Cause: Headers don’t specify application/json or correct charset.
- Fix: Set Content‑Type: application/json; charset=utf-8 and ensure UTF‑8 encoding.
Example (server):
Content-Type: application/json; charset=utf-8
Common Error Messages by Language/Runtime
- JavaScript (JSON.parse):
- Unexpected token < in JSON at position 0 → likely HTML
- Unexpected end of JSON input → truncated or missing brace
- Unexpected string/number in JSON at position ... → missing comma
- Unexpected token ' in JSON at position ... → single quotes
- Python (json):
- Expecting property name enclosed in double quotes: line X column Y
- Extra data: line X column Y (char Z) → concatenated JSON values
- Invalid control character at: line X column Y (char Z)
- Go (encoding/json):
- invalid character 'x' looking for beginning of value
- invalid character '}' after object key
- Java (Jackson):
- Unexpected character ('x' (code 120))
- Unexpected end‑of‑input within/before object/array
- PHP (json_last_error):
- Syntax error, Malformed UTF‑8 characters, Control character error
Knowing these messages helps you jump straight to the cause.
How to Debug API Responses Safely
- Always log raw text first when a parse fails.
- Confirm headers (Content‑Type) and HTTP status codes.
- Watch for proxies/CDNs injecting HTML error pages.
JavaScript example with safe guards:
async function fetchJSON(url) {
const r = await fetch(url, { headers: { 'Accept': 'application/json' } });
const ct = r.headers.get('content-type') || '';
const text = await r.text();
if (!ct.includes('application/json')) {
console.warn('Non-JSON Content-Type:', ct);
console.warn(text.slice(0, 200));
throw new Error('Expected JSON response');
}
try { return JSON.parse(text); }
catch (e) {
console.error('Raw snippet:', text.slice(0, 200));
throw e;
}
}
Python (requests):
import requests
r = requests.get('https://api.example.com/data', headers={'Accept': 'application/json'})
ct = r.headers.get('Content-Type', '')
text = r.text
if 'application/json' not in ct:
print('Non-JSON Content-Type:', ct)
print(text[:200])
raise ValueError('Expected JSON response')
data = r.json() # will raise if invalid
When JSON Is Valid but Your App Still Fails
Sometimes the parser succeeds, but your logic breaks. Check these:
JSON vs JSON5 vs JSONC (and when to use each)
- JSON (RFC 8259): strict, interoperable, required for APIs and storage.
- JSON5: allows comments, single quotes, trailing commas, etc. Great for config in dev tools—but not for interoperable APIs.
- JSONC: JSON with comments (commonly used in IDE settings). Strip comments before shipping.
Rule of thumb: Author in JSON5/JSONC if it boosts ergonomics, then convert to strict JSON for production. ZenixTools can strip comments/trailing commas and output valid JSON automatically.
Production Checklist
- Syntax hygiene
- Keys in double quotes
- Strings in double quotes; escape quotes, backslashes, control chars
- No comments or trailing commas
- Valid numbers (no leading zeros; no +; no .5 or 1.)
- Avoid NaN/Infinity/undefined
- Unique keys only
- Transport & encoding
- Content‑Type: application/json; charset=utf-8
- Ensure UTF‑8 without BOM
- Gzip/Brotli as needed; verify Content‑Length
- Data contracts
- JSON Schema defined and versioned
- Required vs optional fields documented
- Type guarantees for IDs, dates, and decimals
- Safety & resilience
- Limit payload size; stream large arrays
- Validate before persisting
- Log raw bodies on parse errors (redact secrets)
Copy/paste mini‑checklist for editors:
- ZenixTools JSON Formatter & Validator: format, lint, and pinpoint errors fast; strip comments/trailing commas; convert JSONC/JSON5 to JSON; minify/beautify (https://www.zenixtools.com/)
- jq (CLI): validate and query JSON (jq . file.json)
- Python:
python -m json.tool to pretty‑print/validate
- Ajv (JS): JSON Schema validation
- jsonschema (Python): JSON Schema validation
- Jackson (Java): robust parsing + schema add‑ons
FAQ
Q: Why does JSON require double quotes?
A: The spec defines strings and object member names as double‑quoted for unambiguous parsing across languages.
Q: Can the top‑level be an array or a scalar?
A: Yes, any JSON value is allowed by RFC 8259. Some frameworks expect an object/array; check your tooling.
Q: How do I include a literal backslash or Windows path?
A: Escape backslashes: "C:\Users\Name".
Q: How do I represent dates?
A: Use ISO 8601 strings (e.g., "2026-07-18T10:32:00Z") and document timezone.
Q: Why is my big number changing value?
A: Precision loss. Store as string or use a BigInt‑aware parser.
Q: How do I add comments for configuration?
A: Use JSONC/JSON5 during authoring, then convert to strict JSON for production.
Q: My linter says the JSON is valid but the server rejects it.
A: Validate against the API’s JSON Schema and confirm Content‑Type/charset headers.
References
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
- ECMA‑404: The JSON Data Interchange Standard
- IEEE 754: Floating‑Point Arithmetic
Quick Error → Fix Cheat Sheet
- Trailing comma → remove the last comma
- Single quotes → replace with double quotes
- Unescaped quotes/newlines → use escapes (", \n)
- Missing comma → add comma between items
- Comments → remove or pre‑process JSONC
- NaN/Infinity/undefined → use null or strings
- Leading zero numbers → remove leading zero or quote as string
- Duplicate keys → ensure uniqueness
- HTML response → inspect body and headers; fix endpoint/status
- BOM → save as UTF‑8 without BOM; strip \uFEFF
- Big ints → store as strings or parse with BigInt
- Mismatched braces/brackets → pretty‑print and balance
- Backslashes → escape as \
- Multiple values/extra data → use an array or NDJSON
- Invalid numbers (+, 1., .5) → use 5, 1.0, 0.5
- Control characters → escape as \n, \t, \r
- Wrong Content‑Type → set application/json; charset=utf-8
Closing Advice
JSON is simple but unforgiving. Most issues are fixed by correcting quotes, commas, escapes, or invalid values—and by validating early. Adopt a validator in your editor/CI and enforce schemas to catch problems before they ship.
Need a fast fix right now? Paste your payload into ZenixTools: it will format, reveal the exact error position, and convert JSONC/JSON5 to strict JSON instantly. https://www.zenixtools.com/