HomeBlog → JSON SyntaxError Guide

Fix JSON SyntaxError: Every Cause Explained with Examples (2026)

📅 Updated April 2026 ⏱ 11 min read 🛠 Debugging guide

Few error messages are as cryptic as SyntaxError: Unexpected token ',' in JSON at position 42. The error tells you something is wrong, but locating and fixing the exact problem in a large JSON document can be a frustrating exercise. This guide walks through every known cause of JSON parse failures — from the mundane trailing comma to the invisible Byte Order Mark — with a before/after example for each one so you can identify and fix the issue immediately.

Validate your JSON instantly

Paste your JSON below — the validator shows the exact line and character of any error.

Open JSON Validator →

What Causes JSON SyntaxError?

A JSON SyntaxError is thrown by a JSON parser when the input text does not conform to the JSON grammar defined in RFC 8259. JSON parsers are strict by design — unlike web browsers interpreting HTML, a JSON parser has zero tolerance for deviations from the specification.

When you call JSON.parse() in JavaScript and it fails, the error message varies by runtime:

All of these point to the same underlying issue: a character appeared in the JSON where the parser did not expect it. The position tells you where parsing failed — though the actual mistake is sometimes a few characters earlier (for example, a missing closing quote shifts all position numbers).

1 Trailing Commas

This is the single most common JSON error, particularly among JavaScript developers who are accustomed to writing JavaScript objects and arrays where trailing commas are legal (since ES5). In JSON, a trailing comma after the last item is a hard syntax error.

Trailing Comma in an Object

❌ Invalid — comma after the last property

{
  "name": "Alice",
  "age": 28,
  "city": "London",   ← trailing comma — INVALID in JSON
}

✅ Valid — no comma after the last property

{
  "name": "Alice",
  "age": 28,
  "city": "London"
}

Trailing Comma in an Array

❌ Invalid — comma after the last element

{
  "colors": ["red", "green", "blue",]
}

✅ Valid

{
  "colors": ["red", "green", "blue"]
}

If you frequently work with config files and want trailing commas, consider using JSONC (JSON with Comments) format — supported by VS Code's settings.json — or JSON5. However, be aware that JSON.parse() will reject both; you need a dedicated parser.

2 Single Quotes Instead of Double Quotes

JSON requires double quotes for all string values and all property keys. Single quotes are not valid JSON. This error is very common when copying a Python dictionary literal (which uses single quotes by default) and expecting it to be valid JSON.

❌ Invalid — single quotes used for strings and keys

{'name': 'Alice', 'age': 28}

✅ Valid — double quotes throughout

{"name": "Alice", "age": 28}

In Python, if you have a dict and want JSON, always use json.dumps() to serialize it — never use str() or f-strings:

import json
data = {'name': 'Alice', 'age': 28}

# WRONG: str() produces Python dict syntax, not JSON
print(str(data))        # {'name': 'Alice', 'age': 28} — INVALID JSON

# CORRECT: json.dumps() produces valid JSON
print(json.dumps(data)) # {"name": "Alice", "age": 28} — VALID JSON

3 Unquoted Property Keys

JavaScript object literals allow unquoted keys: { name: "Alice" }. This is valid JavaScript, but it is not valid JSON. JSON requires every key to be a double-quoted string, no exceptions.

❌ Invalid — keys are not quoted

{ name: "Alice", age: 28, active: true }

✅ Valid — all keys are double-quoted strings

{ "name": "Alice", "age": 28, "active": true }

This distinction exists because JSON is designed as a language-independent data interchange format, not a subset of JavaScript. Keys are always strings to ensure unambiguous parsing across all languages.

4 Comments in JSON

Standard JSON does not support comments of any kind. There is no // line comment, no /* */ block comment, and no # hash comment. This is a deliberate design decision by Douglas Crockford, who removed comments from the JSON specification to prevent people from using comments as parsing directives (as happened with Internet Explorer's conditional comments).

❌ Invalid — comments are not allowed in JSON

{
  // User configuration
  "theme": "dark",   /* UI preference */
  "language": "en"   # locale setting
}

✅ Valid — comments removed

{
  "theme": "dark",
  "language": "en"
}

Alternatives to JSON Comments

If you need comments in a config file, consider these alternatives:

// Convention: using "_comment" keys for documentation
{
  "_comment": "Production database config — do not edit without review",
  "host": "db.prod.example.com",
  "port": 5432
}

5 Undefined, NaN, and Infinity Values

JavaScript's undefined, NaN, and Infinity are not valid JSON values. The complete set of valid JSON value types is: string, number, object, array, true, false, and null. No other identifiers are valid.

❌ Invalid — undefined, NaN, Infinity are not JSON values

{
  "unset": undefined,
  "ratio": NaN,
  "limit": Infinity,
  "debt": -Infinity
}

✅ Valid — replace with null or a numeric equivalent

{
  "unset": null,
  "ratio": null,
  "limit": 1.7976931348623157e+308,
  "debt": -1.7976931348623157e+308
}

Note that JSON.stringify() silently drops properties with undefined values and converts standalone undefined, NaN, and Infinity to null:

JSON.stringify({ a: undefined, b: NaN, c: Infinity })
// Result: '{"b":null,"c":null}'
// Note: property "a" is completely omitted, not set to null

6 Leading Zeros on Numbers

JSON does not allow numeric values with leading zeros (except for the decimal number 0.something). A number like 007 or 042 looks like an octal literal to many parsers and is explicitly forbidden by the JSON specification.

❌ Invalid — leading zeros on integer values

{
  "agentId": 007,
  "code": 042,
  "year": 02024
}

✅ Valid — no leading zeros, or use strings if zero-padding matters

{
  "agentId": 7,
  "code": 42,
  "year": 2024,
  "formattedId": "007"
}

If your data requires zero-padded identifiers (like employee codes "0042"), store them as strings rather than numbers. This preserves the formatting and is unambiguous JSON.

7 Unescaped Special Characters in Strings

Several characters are forbidden inside JSON string literals unless they are escaped with a backslash. The most commonly encountered are the literal newline (U+000A), carriage return (U+000D), and the double quote (U+0022). Pasting multi-line text from a word processor or database into a JSON string is the most common cause of this error.

❌ Invalid — raw newline inside the string value

{
  "address": "123 Main Street
              Springfield, IL 62701"
}

✅ Valid — newline replaced with \n escape

{
  "address": "123 Main Street\n              Springfield, IL 62701"
}

See the JSON Escape/Unescape Guide for a complete reference of all escape sequences and the Escape/Unescape tool to fix these automatically.

8 Mismatched Brackets and Braces

Every opening { must have a matching closing }, and every [ must have a matching ]. Mismatched or missing brackets are common in deeply nested JSON, especially when editing manually. The parser typically reports the error at the position where it encountered an unexpected closing character or end of input.

❌ Invalid — array closed with } instead of ]

{
  "user": {
    "name": "Alice",
    "tags": ["admin", "editor"}  ← wrong closing bracket
  }
}

✅ Valid — correct closing brackets

{
  "user": {
    "name": "Alice",
    "tags": ["admin", "editor"]
  }
}

Counting Technique

For large documents, use the counting technique: scan the JSON and maintain two counters — one for {/} pairs and one for [/] pairs. At the end of the document, both counters must be zero. Any non-zero count tells you exactly how many unmatched brackets remain. Your editor's bracket-matching feature or the JSON Validator tool will pinpoint the mismatch automatically.

9 Duplicate Keys

Duplicate keys in a JSON object are technically permitted by the RFC 8259 specification ("SHOULD be unique" is advisory, not required), but their behavior is undefined — different parsers handle them differently. JavaScript's JSON.parse() silently keeps the last value; Python's json.loads() also keeps the last value; some parsers raise an error.

// Both keys parse without error in JavaScript
JSON.parse('{"name": "Alice", "name": "Bob"}')
// Result: { name: "Bob" }  — first value silently discarded

// In Python
import json
json.loads('{"name": "Alice", "name": "Bob"}')
# Result: {'name': 'Bob'}  — same silent overwrite

While duplicate keys rarely cause a hard SyntaxError, they indicate a data quality issue and can cause hard-to-debug bugs when the first value is silently discarded. Use the JSON Validator with the "warn on duplicate keys" option to detect them.

10 BOM (Byte Order Mark)

A Byte Order Mark (BOM) is a special Unicode character (U+FEFF) that some text editors, particularly on Windows, prepend to UTF-8 files. It is invisible in most text editors but immediately breaks a JSON parser because the parser encounters the BOM character before the expected opening { or [.

The error looks like: SyntaxError: Unexpected token in JSON at position 0 — note the invisible character before "in". The fix is to strip the BOM from the file:

// JavaScript: strip BOM before parsing
const jsonText = rawText.replace(/^\uFEFF/, '');
const data = JSON.parse(jsonText);

// Python: use 'utf-8-sig' encoding to strip BOM automatically
with open('data.json', 'r', encoding='utf-8-sig') as f:
    data = json.load(f)

# Command line: strip BOM with sed
sed -i '1s/^\xEF\xBB\xBF//' data.json

To prevent BOM issues, configure your text editor to save files in UTF-8 without BOM. In VS Code, click the encoding indicator in the status bar and choose "Save with Encoding" → "UTF-8".

11 Missing Commas Between Properties

Each property in a JSON object and each element in a JSON array must be separated by a comma. Forgetting a comma between two consecutive properties is easy to do when editing JSON manually, especially after reordering lines.

❌ Invalid — missing comma between properties

{
  "firstName": "Alice"
  "lastName": "Smith"
  "email": "alice@example.com"
}

✅ Valid — commas after each property except the last

{
  "firstName": "Alice",
  "lastName": "Smith",
  "email": "alice@example.com"
}

How to Debug JSON Errors Step by Step

When you encounter a JSON parse error, work through these steps methodically:

  1. Read the error message carefully. Note the position or line number reported. Modern runtimes like Node.js v20+ provide very precise position information.
  2. Go to the reported position. Open your JSON in a text editor that shows line and column numbers. Navigate to the reported position — the error is usually at or just before that character.
  3. Check the character at the error position. Is it a comma that should not be there? A single quote? A backslash that breaks an escape sequence?
  4. Check one line before the error position. Many errors are caused by something missing (a closing quote, a comma) that makes the parser fail on the next valid character.
  5. Use an online validator. The JSON Validator tool shows a highlighted error with a description. This is often faster than reading raw error messages.
  6. Divide and conquer for large files. Remove half the JSON and check if the error is in the first half or the second half. Repeat until you isolate the problematic section.

Using JSON Repair Tools

For common, automatable errors — trailing commas, single quotes, missing quotes on keys, and similar issues — a JSON repair tool can fix your JSON automatically without requiring manual editing. The JSON Repair tool at jsonwebtools.com handles the most common error patterns:

Auto-repair tools are best used for JSON that was generated by code with minor formatting deviations. For JSON with structural problems like mismatched brackets or misplaced data, manual review is still necessary.

Frequently Asked Questions

What causes JSON SyntaxError: Unexpected token? +
The most common causes are: trailing commas after the last item in an object or array, single quotes instead of double quotes, unquoted property keys, JavaScript-style comments (// or /* */), undefined or NaN values, and unescaped special characters like newlines or raw double quotes inside strings.
Does JSON allow trailing commas? +
No. Standard JSON does not allow trailing commas. This is one of the most common JSON errors, especially among JavaScript developers accustomed to ES5+ object syntax. JSONC (JSON with Comments) does allow trailing commas, but standard JSON.parse() will reject them with a SyntaxError.
Can JSON have comments? +
No. Standard JSON does not support any kind of comments. If you need comments, use JSONC (supported by VS Code), JSON5, or strip comments before parsing with a library like strip-json-comments. As a workaround, you can add a "_comment" key with a string value, though this is a data field, not a real comment.
What values are not valid in JSON? +
JavaScript values undefined, NaN, Infinity, and -Infinity are not valid JSON. Functions, Symbols, and Dates (as objects) are also not valid. Valid JSON value types are: string, number (finite), object, array, true, false, and null.
How do I find which line has the JSON error? +
Paste your JSON into the JSON Validator at jsonwebtools.com — it highlights the exact line and character of the error with a plain-language description. In JavaScript, JSON.parse() includes position information in the error message. On the command line, cat data.json | jq . shows parse error at line N, column M.

Related Tools & Guides

JSON Validator  |  JSON Repair Tool  |  JSON Formatter  |  JSON Escape Guide  |  How to Validate JSON