Fix Invalid JSON Error: Step-by-Step Troubleshooting Guide
You pasted JSON into your app, your API call failed, or your config file won't load - and all you have is a cryptic error message like SyntaxError: Unexpected token. This guide walks through every common JSON parse error, shows you exactly where it happens, and tells you how to fix it.
Why JSON Errors Are So Common
JSON syntax is strict by design. Unlike JavaScript objects (which inspired it), JSON has zero tolerance for trailing commas, single quotes, comments, or unquoted keys. Most JSON errors come from one of two sources: JSON written by hand by a developer who unconsciously applied JavaScript rules, or JSON generated by string concatenation instead of a proper serializer.
The frustrating part is that the error message rarely tells you exactly what went wrong in plain language. Unexpected token '}' at position 47 gives you a location but not a cause. This guide bridges that gap.
Step 1 - Read the Error Message Carefully
Before trying random fixes, extract three pieces of information from the error:
- The token: What unexpected character did the parser encounter? A
}, a', a letter? - The position or line number: Most parsers give you a character offset or line/column. Use this to navigate directly to the problem.
- The parser context: Was it expecting a property name? A value? A comma?
For example, SyntaxError: Unexpected token } in JSON at position 31 tells you the parser hit a closing brace when it was expecting something else - almost always a missing comma or a trailing comma that caused the parser to get out of sync.
The reported error position is where the parser gave up, not necessarily where you made the mistake. The actual error is often a few characters before the reported position.
Step 2 - Identify the Error Type
JSON parse errors fall into a handful of well-defined categories. Match your error message to one of these to know exactly what to look for.
Error Type 1: Trailing Comma
This is the single most common JSON mistake, especially for developers coming from JavaScript, Python, or Ruby where trailing commas are perfectly fine.
Broken example:
{
"name": "Alice",
"role": "admin",
"active": true,
}
Fixed:
{
"name": "Alice",
"role": "admin",
"active": true
}
The same rule applies inside arrays. ["a", "b", "c",] is invalid. The last element must have no trailing comma. If you generate JSON programmatically, always use JSON.stringify() (JavaScript), json.dumps() (Python), or your language's built-in serializer - they never produce trailing commas.
Error Type 2: Single Quotes Instead of Double Quotes
JSON strictly requires double quotes for both keys and string values. Single quotes are not valid JSON, even though they are perfectly valid in JavaScript object literals.
Broken example:
{
'name': 'Alice',
'role': 'admin'
}
Fixed:
{
"name": "Alice",
"role": "admin"
}
A global find-and-replace of ' with " will work if your string values themselves don't contain apostrophes. If they do, you need to be more careful - replace only the quote characters that delimit keys and values.
Error Type 3: Unquoted Keys
JavaScript object literals allow unquoted keys: {name: "Alice"}. JSON does not. Every key must be a double-quoted string.
Broken example:
{
name: "Alice",
role: "admin"
}
Fixed:
{
"name": "Alice",
"role": "admin"
}
This often happens when developers copy a JavaScript object literal from source code and try to use it as JSON directly.
Error Type 4: Missing Comma Between Properties
Every key-value pair in a JSON object must be separated by a comma - except the last one. A missing comma causes the parser to see two consecutive values where it expected a comma or closing bracket.
Broken example:
{
"name": "Alice"
"role": "admin"
}
Fixed:
{
"name": "Alice",
"role": "admin"
}
Error Type 5: Unescaped Special Characters in Strings
Certain characters inside JSON strings must be escaped with a backslash. The most commonly forgotten ones are:
- Backslash:
\must become\\ - Double quote inside a string:
"must become\" - Newline: literal newlines inside a string value are not allowed - use
\n - Tab: literal tab characters must be
\t - Control characters: characters with code points below U+0020 must be Unicode-escaped as
\uXXXX
Broken example (Windows file path):
{
"configPath": "C:\Users\Alice\config.json"
}
Fixed:
{
"configPath": "C:\\Users\\Alice\\config.json"
}
This is a very common issue when embedding file paths, regular expressions, or LaTeX strings in JSON.
Error Type 6: Unexpected End of Input
The parser reached the end of the input before the JSON structure was complete. This means you have an unclosed object { or array [ somewhere.
Broken example:
{
"name": "Alice",
"roles": [
"admin",
"editor"
}
Fixed:
{
"name": "Alice",
"roles": [
"admin",
"editor"
]
}
The array was never closed with ]. When debugging this type of error, count your opening and closing braces and brackets - they must balance perfectly.
Error Type 7: Comments in JSON
JSON does not support comments of any kind. No // line comments, no /* block comments */. This surprises many developers because JavaScript (the language JSON is based on) supports both.
Broken example:
{
// Database configuration
"host": "localhost",
"port": 5432 /* default Postgres port */
}
Fixed: Remove all comments. If you need comments in configuration files, consider using YAML (which supports comments) or the .jsonc format supported by VS Code and some tools.
Error Type 8: Invalid Number Formats
JSON numbers must be standard decimal notation. Several number formats that work in JavaScript are invalid in JSON:
- Leading zeros:
07is invalid (looks like octal). Use7. - Hexadecimal:
0xFFis not valid JSON. Use the decimal equivalent255. - NaN:
NaNis not a valid JSON value. Usenullor omit the field. - Infinity:
Infinityand-Infinityare not valid JSON values. - Trailing decimal point:
1.is invalid. Use1.0or1.
Error Type 9: BOM (Byte Order Mark)
Some text editors - particularly on Windows - prepend an invisible UTF-8 BOM (0xEF 0xBB 0xBF) to files. This causes a SyntaxError: Unexpected token at position 0 because the parser sees the BOM character before the opening {. The fix is to save the file without BOM, or strip the BOM character. Our JSON Formatter handles this automatically.
Fix Your JSON Instantly
Paste your broken JSON and get the exact error with line and column numbers, syntax highlighting, and a formatted output. Free, runs entirely in your browser - nothing is sent to any server.
Open JSON Formatter & ValidatorStep 3 - How to Locate the Exact Error Position
Once you know the error type, finding the exact location is the next challenge. Here are three reliable techniques:
Technique 1: Use a JSON Validator with Line Numbers
Paste your JSON into our JSON Formatter. It highlights the exact line and character where parsing fails, so you can jump directly to the problem rather than scanning hundreds of lines manually.
Technique 2: Binary Search with JSON.parse()
If you are working with a large JSON file in a terminal, use this approach in Node.js:
const fs = require('fs');
try {
JSON.parse(fs.readFileSync('broken.json', 'utf8'));
console.log('Valid!');
} catch (e) {
console.error(e.message);
// Output: "Unexpected token } in JSON at position 847"
}
The position number tells you the character offset. Open the file and navigate to that character. The actual error is usually within the preceding 20 characters.
Technique 3: Use jq on the Command Line
jq is a command-line JSON processor that provides very precise error messages:
cat broken.json | jq .
# parse error (Expected separator between values) at line 4, column 12
jq gives line and column numbers, which is often more useful than a character offset.
Step 4 - Fix the Error
With the location and type identified, apply the fix from the table above. A few tips to avoid re-introducing errors:
- Always use your language's native JSON serializer to generate JSON - never build JSON with string concatenation.
- In JavaScript,
JSON.stringify(obj, null, 2)always produces valid, pretty-printed JSON. - In Python,
json.dumps(obj, indent=2)does the same. - Enable JSON syntax highlighting in your editor so errors are visually obvious before you even run the code.
Step 5 - Validate the Fix Programmatically
After making your edits, validate the corrected JSON before shipping it. Here are quick one-liners for common languages:
JavaScript / Node.js
try {
const data = JSON.parse(yourJsonString);
console.log('Valid JSON:', data);
} catch (e) {
console.error('Invalid JSON:', e.message);
}
Python
import json
try:
data = json.loads(your_json_string)
print("Valid JSON:", data)
except json.JSONDecodeError as e:
print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")
Python's JSONDecodeError is particularly helpful because it gives you lineno and colno directly on the exception object.
PHP
$data = json_decode($jsonString, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo 'Invalid JSON: ' . json_last_error_msg();
} else {
echo 'Valid JSON';
}
Bash (using jq)
echo "$JSON_STRING" | jq . > /dev/null 2>&1 \
&& echo "Valid" \
|| echo "Invalid JSON"
Real Before/After Examples
Here are three realistic scenarios that combine multiple error types at once - the kind of JSON you might receive from a third-party API or a non-developer teammate.
Example 1: Config file written by hand
Before (3 errors):
{
// App configuration
'environment': 'production',
'debug': false,
'database': {
'host': 'localhost',
'port': 5432,
}
}
After:
{
"environment": "production",
"debug": false,
"database": {
"host": "localhost",
"port": 5432
}
}
Fixed: removed comment, changed single quotes to double quotes, removed trailing comma after 5432.
Example 2: Copy-pasted from a JavaScript source file
Before:
{
name: "Product Launch",
tags: ["new", "featured",],
metadata: {
created: new Date()
}
}
After:
{
"name": "Product Launch",
"tags": ["new", "featured"],
"metadata": {
"created": "2026-03-26T00:00:00Z"
}
}
Fixed: quoted keys, removed trailing comma in array, replaced new Date() with an ISO 8601 string (JavaScript expressions are not valid JSON values).
Example 3: Windows file path embedded in JSON
Before:
{
"logFile": "C:\Program Files\App\logs\app.log",
"tempDir": "C:\Users\Alice\AppData\Local\Temp"
}
After:
{
"logFile": "C:\\Program Files\\App\\logs\\app.log",
"tempDir": "C:\\Users\\Alice\\AppData\\Local\\Temp"
}
How to Prevent JSON Errors Going Forward
Once you fix the immediate error, put systems in place to catch JSON errors automatically:
- Never hand-write production JSON. Always serialize from a data structure using your language's standard library.
- Lint your JSON files in CI. Add
jq . config.jsonas a CI step - it exits non-zero on invalid JSON. - Use JSON Schema to validate structure, not just syntax. A syntactically valid JSON document can still be semantically wrong (missing required fields, wrong types). Use our JSON Schema Validator to catch these issues.
- Configure your editor. VS Code, JetBrains IDEs, and Vim with ALE all support JSON syntax validation in real time. Enable it.
- For config files that need comments, use YAML or TOML instead of JSON. They support comments natively and are equally well-supported in most ecosystems.
Frequently Asked Questions
What does "SyntaxError: Unexpected token u in JSON at position 0" mean?
This error almost always means the value you passed to JSON.parse() is undefined, not a JSON string. JavaScript converts undefined to the string "undefined" before passing it, and JSON.parse("undefined") fails immediately because u is not a valid JSON token. Check that the variable you are parsing is actually populated - it is likely an empty API response, a failed fetch, or an uninitialized variable.
What does "SyntaxError: Unexpected end of JSON input" mean?
The JSON string you passed to the parser is empty (""), or the JSON is truncated (incomplete). Common causes: a network response was cut off, a file read failed mid-way, or you accidentally passed an empty string. Add a check for empty input before calling JSON.parse(), and verify the full response body was received.
Can JSON have comments?
No. The official JSON specification (RFC 8259) does not allow comments. This is an intentional design decision by Douglas Crockford, who removed comment support from JSON to prevent people from using comments to hold parsing directives (as happened in Internet Explorer with conditional comments). If you need comments in a config file, use YAML, TOML, or .jsonc (JSON with Comments) which is supported by VS Code, TypeScript's tsconfig.json, and many other tools.
Why does my JSON work in JavaScript but fail in a JSON parser?
JavaScript's eval() and object literal syntax are a superset of JSON - they accept trailing commas, single quotes, unquoted keys, and comments. A strict JSON parser (like JSON.parse() in any language, or any JSON validator) only accepts valid JSON as defined by the spec. If your JSON works with eval() but not JSON.parse(), you have one of the issues described in this guide. Fix the source to produce standard JSON.
How do I fix JSON with duplicate keys?
Duplicate keys are technically not forbidden by the JSON specification, but they produce undefined behavior - different parsers handle them differently. Some take the last value, some the first, some throw an error. The fix is to remove the duplicate and decide which value you intended to keep. Our JSON Formatter will warn you about duplicate keys when it detects them.
What is the fastest way to fix JSON online?
Paste it into our JSON Formatter. It runs entirely in your browser, highlights the exact error position, tells you the error type, and shows you a formatted version of the corrected JSON once the error is resolved. No signup, no data sent to any server.
Related reading: JSON Formatting Best Practices · JSON Schema Validator · JSON Diff Checker
Validate and Fix Your JSON Now
Paste any broken JSON - our formatter highlights the exact error, explains the cause, and shows you the corrected output. Free, instant, no account required.
Use the Free JSON Formatter →Usman has 10+ years of experience securing enterprise infrastructure, managing high-traffic servers, and building zero-knowledge security tools. Read more about the author.