JSON Parse Error: Complete Guide
A JSON parse error occurs when a parser attempts to read a JSON string but encounters syntax that violates the RFC 8259 specification. The parser cannot continue and throws an exception, commonly halting your API call, crashing your build pipeline, or returning a 500 error to your end users.
Unlike runtime errors that surface only under certain conditions, JSON parse errors are deterministic — the same malformed input will always produce the same error. That means they are entirely preventable and, once you know what to look for, quick to fix.
Common JSON Parse Error Messages
The exact error message you see depends on the runtime or language. Here is a quick reference:
| Environment | Typical Error Message |
|---|---|
| JavaScript (V8) | SyntaxError: Unexpected token ',' in JSON at position 42 |
| JavaScript (V8 / Node 20+) | SyntaxError: Expected ',' or '}' after property value in JSON at position 42 |
| Python | json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) |
| Java (Jackson) | com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)) at [Source: …] |
| Go (encoding/json) | invalid character '\'' looking for beginning of object key string |
| Rust (serde_json) | expected value at line 1 column 1 |
| PHP | json_last_error() returns JSON_ERROR_SYNTAX (4) |
| C# (System.Text.Json) | JsonException: ''' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0. |
All of these ultimately mean the same thing: the parser found a character or structure it did not expect. The position number in the message is your breadcrumb — count to that character offset in your raw string to find the offending syntax.
Cause 1: Trailing Commas
Trailing commas are the single most frequent cause of JSON parse errors. A trailing comma is a comma placed after the last item in an object or array.
{
"name": "Alice",
"age": 30,
}{
"name": "Alice",
"age": 30
}Trailing commas are legal in JavaScript, Python, and many other languages — which is why developers keep writing them instinctively. JSON has zero tolerance for them. Remove the comma after the last property or array element and the error disappears.
Quick Fix
Paste your JSON into our JSON Formatter and click Format. It automatically strips trailing commas and re-serialises a clean copy.
Cause 2: Single Quotes Instead of Double Quotes
JSON mandates double quotes for both property names and string values. Single quotes are a JavaScript convenience that the JSON specification explicitly prohibits.
{ 'user': 'Alice', 'active': true }{ "user": "Alice", "active": true }This error is especially common when copying object literals from JavaScript source code directly into a JSON file, or when an LLM generates output with inconsistent quoting.
Cause 3: Unquoted Property Keys
JavaScript object keys can be unquoted if they are valid identifiers. JSON keys must always be quoted strings.
{ id: 1, name: "Alice" }{ "id": 1, "name": "Alice" }Cause 4: Comments
JSON does not support comments of any kind — not // single-line comments, not /* */ block comments. If your JSON file contains comments (perhaps copied from a JSONC config file), every parser will throw.
{
// Primary user record
"id": 42,
"name": "Alice" /* display name */
}{
"id": 42,
"name": "Alice"
}If you need human-readable config files with comments, consider switching to YAML or TOML, both of which natively support comments and are easily convertible.
Cause 5: Undefined, NaN, and Infinity Values
JSON only supports six value types: string, number, boolean (true/false), null, object, and array. The JavaScript values undefined, NaN, and Infinity are not part of the JSON specification and will cause a parse error if present in serialised output.
{
"score": NaN,
"limit": Infinity,
"callback": undefined
}{
"score": null,
"limit": null
}In JavaScript, JSON.stringify() silently drops undefined properties and converts NaN and Infinity to null. If you are reading JSON serialised by another system, replace these sentinel values with null before parsing.
Cause 6: Unexpected Token at Position 0 (HTML Response)
The error "Unexpected token '<' in JSON at position 0" is one of the most searched JSON parse errors online. The < character is the first character of an HTML document (<!DOCTYPE html> or <html>). It means your code expected a JSON response but received an HTML page instead.
Common causes:
- Server returned a 404/500 error page: The endpoint does not exist or the server crashed before it could serialise JSON.
- Incorrect Content-Type header: The server sent
text/htmlinstead ofapplication/json, and a proxy or CDN intercepted the request. - Redirect to a login page: An authentication middleware redirected the unauthenticated API request to an HTML login screen.
- Wrong URL: A typo in the endpoint path resolves to an existing HTML page.
Debug with DevTools
Open your browser's Network tab, find the failing request, and click the Response sub-tab. You can immediately see the raw server response. If it starts with <!DOCTYPE or <html>, the problem is server-side — fix the endpoint, not the parser.
Cause 7: Truncated or Incomplete JSON
Truncated JSON — a response that was cut off before the closing } or ] — is increasingly common in AI-powered workflows. Large Language Models have a hard output token limit; if the generated JSON exceeds that limit, the response is clipped mid-structure.
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob"Other causes of truncated JSON include network timeouts, streaming reads that were terminated early, and file writes that were interrupted. The parser will throw an "Unexpected end of JSON input" error (or equivalent).
Cause 8: BOM (Byte Order Mark)
Some text editors (particularly on Windows) save UTF-8 files with a BOM — three invisible bytes (0xEF 0xBB 0xBF) prepended to the file. These bytes make the JSON string start with a non-JSON character, causing "Unexpected token \uFEFF in JSON at position 0".
The fix is to re-save the file as UTF-8 without BOM. In VS Code, click the encoding indicator in the status bar (bottom-right) and choose Save with Encoding → UTF-8. In Node.js you can strip the BOM programmatically:
const fs = require('fs');
let raw = fs.readFileSync('./data.json', 'utf8');
// Remove UTF-8 BOM if present
if (raw.charCodeAt(0) === 0xFEFF) {
raw = raw.slice(1);
}
const data = JSON.parse(raw);How to Debug a JSON Parse Error
The character position reported in the error message is the fastest path to the root cause. Here is a systematic approach:
- Read the full error message. Note the position number (e.g. "at position 42") or the line/column (e.g. "line 3 column 8").
- Isolate the raw string. Log the raw string before calling
JSON.parse(). Do not log the parsed result — you want the exact bytes that the parser received. - Navigate to the reported position. Paste the raw string into a text editor, then jump to that character offset. The error is almost always within a few characters of that position.
- Paste into a validator. Our JSON Validator highlights every syntax error inline with a human-readable explanation.
- Check the source, not just the string. If the JSON comes from an API or file, verify that the source hasn't changed format (e.g., started returning HTML on error).
Language-Specific Fixes
JavaScript / Node.js
Always wrap JSON.parse() in a try/catch block so a bad payload does not crash your entire process:
function safeParseJSON(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (err) {
console.error('JSON parse error:', err.message);
return { data: null, error: err.message };
}
}
const { data, error } = safeParseJSON(rawString);
if (error) {
// Handle gracefully — show user a message, retry, etc.
}Python
Use a try/except block and catch json.JSONDecodeError (a subclass of ValueError). The exception exposes useful .lineno and .colno attributes:
import json
def safe_parse(raw: str):
try:
return json.loads(raw)
except json.JSONDecodeError as e:
print(f"JSON parse error at line {e.lineno}, col {e.colno}: {e.msg}")
return None
data = safe_parse(raw_string)Java (Jackson)
Catch JsonProcessingException and inspect the getLocation() method for the exact offset:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
ObjectMapper mapper = new ObjectMapper();
try {
MyDto dto = mapper.readValue(rawJson, MyDto.class);
} catch (JsonProcessingException e) {
System.err.println("Parse error at: " + e.getLocation());
System.err.println("Message: " + e.getOriginalMessage());
}Go
The encoding/json package returns a typed *json.SyntaxError with an Offset field:
import (
"encoding/json"
"fmt"
)
var result map[string]interface{}
if err := json.Unmarshal([]byte(raw), &result); err != nil {
if syntaxErr, ok := err.(*json.SyntaxError); ok {
fmt.Printf("Syntax error at offset %d: %s\n", syntaxErr.Offset, err)
}
}How to Fix JSON Parse Errors Automatically
For interactive debugging, our suite of free tools handles the most common parse errors automatically:
- JSON Formatter & Repair: Strips trailing commas, adds missing quotes, removes comments, and re-serialises valid JSON.
- JSON Validator: Highlights every syntax violation inline with an explanation and the exact character position.
- JSON Minifier: Normalises whitespace and compresses the payload — useful for catching hidden characters.
For programmatic repair in production, consider a lenient parser library such as json5 (JavaScript/Node.js) or demjson3 (Python) that tolerates common human errors and converts them to strict JSON. Use these as a sanitisation step in your ingestion pipeline, not as a permanent workaround.
Best Practices to Prevent JSON Parse Errors
- Always validate at system boundaries. Parse and validate JSON immediately when it enters your system from an external API, message queue, or file upload — never pass raw strings deep into business logic.
- Use a JSON schema. Define the expected shape with JSON Schema and validate all incoming payloads against it. Our JSON to Schema Generator creates a schema from any sample payload in one click.
- Set explicit Content-Type headers. When building an API, always return
Content-Type: application/jsonand use a proper JSON serialiser — never concatenate JSON strings manually. - Avoid manual JSON construction. Use your language's built-in serialiser (
JSON.stringify,json.dumps,ObjectMapper.writeValueAsString) rather than building JSON by string concatenation. - Log raw payloads on error. Before calling
JSON.parse(), log the raw string atdebuglevel. You will be very grateful the first time a third-party API starts returning HTML error pages. - Lint JSON files in CI. Add a
jsonlintorprettier --checkstep to your CI pipeline so malformed JSON config files are caught before they reach production.
JSON Parse Error vs. JSON Validation Error
These two terms are often conflated but represent different problems:
| Parse Error | Validation Error | |
|---|---|---|
| What it means | The JSON is not syntactically valid — the parser cannot even read it. | The JSON is syntactically valid but does not match the expected schema or business rules. |
| When it happens | Immediately on calling JSON.parse() / json.loads() | After parsing, during schema or domain validation. |
| Example | Missing closing bracket, trailing comma, single quote | String where an integer is expected, required field is absent |
| Fix | Repair the syntax | Reject the payload, return a 400, notify the sender |
Tip: Schema Validation Catches Both
A JSON Schema validator such as Ajv (JavaScript) or jsonschema (Python) will first parse the document and then validate its structure. If you add schema validation at your API layer you get both levels of protection in one step. Generate your schema instantly with our Schema Generator.
Fix Your JSON Parse Error Now
Paste your broken JSON into our free formatter. It repairs trailing commas, single quotes, missing brackets, and more — instantly.