{
"loading": true
"progress": ...
}
JSON Formatters Pro
JSON Tutorials

How to Fix JSON Syntax Errors: Complete Troubleshooting Guide (2026)

πŸ“… December 10, 2025 ⏱️ 7 min read πŸ‘οΈ 6 views 🏷️ JSON Tutorials

There's nothing more frustrating than hitting a JSON syntax error that breaks your application. Whether you're working with APIs, configuration files, or data processing, JSON errors can stop you in your tracks.

In this comprehensive guide, we'll cover the most common JSON syntax errors, how to identify them, and exactly how to fix them. By the end, you'll be able to debug any JSON issue like a pro!

Table of Contents

Understanding JSON Errors

Before diving into specific errors, let's understand how JSON parsing works:

try {
  const data = JSON.parse(jsonString);
  console.log('Valid JSON!', data);
} catch (error) {
  console.error('JSON Error:', error.message);
  // Example: "Unexpected token } at position 45"
}

Error messages typically include:

  • Unexpected token: The parser found a character it didn't expect
  • Position: The character index where the error occurred
  • Line/Column: Some parsers provide line and column numbers

Error 1: Trailing Commas

This is the #1 most common JSON error. A trailing comma is a comma after the last item in an object or array.

The Error

// ❌ INVALID - Trailing comma after "age"
{
  "name": "Alice",
  "age": 25,
}

// ❌ INVALID - Trailing comma in array
{
  "colors": ["red", "green", "blue",]
}

The Fix

// βœ… VALID - No trailing comma
{
  "name": "Alice",
  "age": 25
}

// βœ… VALID - No trailing comma in array
{
  "colors": ["red", "green", "blue"]
}

Why This Happens

Trailing commas are allowed in JavaScript objects and arrays, so developers often accidentally include them in JSON. Remember: JSON is stricter than JavaScript!

Prevention Tips

// Use JSON.stringify to ensure valid output
const obj = {name: "Alice", age: 25};
const validJson = JSON.stringify(obj, null, 2);
// This will never have trailing commas

Error 2: Single Quotes

JSON requires double quotes for strings. Single quotes are not valid.

The Error

// ❌ INVALID - Single quotes
{'name': 'Alice', 'age': 25}

// ❌ INVALID - Mixed quotes
{"name": 'Alice', "age": 25}

The Fix

// βœ… VALID - Double quotes only
{"name": "Alice", "age": 25}

Quick Fix Script

// Replace single quotes with double quotes
function fixQuotes(jsonString) {
  // Be careful - this is a simple fix and may not work in all cases
  return jsonString.replace(/'/g, '"');
}

const fixed = fixQuotes("{'name': 'Alice'}");
console.log(fixed);  // {"name": "Alice"}

Error 3: Unquoted Keys

In JSON, all keys MUST be strings enclosed in double quotes.

The Error

// ❌ INVALID - Unquoted keys
{name: "Alice", age: 25}

// ❌ INVALID - Number as key (valid in JS, not in JSON)
{1: "first", 2: "second"}

The Fix

// βœ… VALID - All keys quoted
{"name": "Alice", "age": 25}

// βœ… VALID - Number keys as strings
{"1": "first", "2": "second"}

JavaScript vs JSON

// JavaScript object - unquoted keys are fine
const jsObj = {name: "Alice", age: 25};

// JSON string - must quote all keys
const jsonStr = '{"name": "Alice", "age": 25}';

Error 4: Comments in JSON

JSON does NOT support comments. Any form of comment will cause a parse error.

The Error

// ❌ INVALID - JavaScript-style comments
{
  "name": "Alice", // User's name
  "age": 25  /* User's age */
}

// ❌ INVALID - HTML-style comments
{
  <!-- Configuration -->
  "debug": true
}

The Fix

// βœ… VALID - No comments allowed
{
  "name": "Alice",
  "age": 25
}

Workarounds for Comments

Option 1: Use a description field

{
  "_comment": "This is a configuration file",
  "_description": "Debug mode enables verbose logging",
  "debug": true
}

Option 2: Use JSON5 (superset of JSON)

// JSON5 supports comments
const JSON5 = require('json5');
const config = JSON5.parse(`{
  // This is a comment
  "debug": true,
}`);

Option 3: Use JSONC (JSON with Comments) in VS Code

VS Code supports .jsonc files that allow comments for configuration.

Error 5: Special Characters

Certain characters must be escaped in JSON strings.

The Error

// ❌ INVALID - Unescaped special characters
{
  "path": "C:\Users\Alice",
  "message": "She said "Hello"",
  "text": "Line 1
Line 2"
}

The Fix

// βœ… VALID - Properly escaped
{
  "path": "C:\\Users\\Alice",
  "message": "She said \"Hello\"",
  "text": "Line 1\nLine 2"
}

Escape Character Reference

CharacterEscape Sequence
Backslash \\\
Double Quote "\"
Newline\n
Tab\t
Carriage Return\r
Unicode\uXXXX

Auto-Escaping with JSON.stringify

const data = {
  path: 'C:\Users\Alice',
  message: 'She said "Hello"'
};

const json = JSON.stringify(data, null, 2);
// Automatically escaped correctly

Error 6: Encoding Issues

JSON should be encoded in UTF-8. Other encodings can cause parse errors.

The Error

// ❌ INVALID - BOM character at start
{Γ―ΒΏΒΏ"name": "Alice"}

// ❌ INVALID - Invalid UTF-8 sequences
{"name": "ΓΏΓΎ"}

The Fix

# Python: Ensure UTF-8 encoding
import json

# Read with UTF-8 encoding
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# Write with UTF-8 encoding
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False)
// Node.js: Handle BOM
const fs = require('fs');

let content = fs.readFileSync('data.json', 'utf-8');

// Remove BOM if present
if (content.charCodeAt(0) === 0xFEFF) {
  content = content.slice(1);
}

const data = JSON.parse(content);

Error 7: Undefined and NaN Values

JSON doesn't support JavaScript's undefined, NaN, or Infinity.

The Error

// ❌ INVALID - undefined is not valid
{"value": undefined}

// ❌ INVALID - NaN is not valid  
{"value": NaN}

// ❌ INVALID - Infinity is not valid
{"value": Infinity}

The Fix

// βœ… VALID - Use null for missing values
{"value": null}

// βœ… VALID - Use string for special numbers
{"value": "NaN"}

// βœ… VALID - Or use a very large number
{"value": 1e308}

JavaScript Conversion

const data = {
  a: undefined,
  b: NaN,
  c: Infinity
};

// JSON.stringify handles these automatically
const json = JSON.stringify(data);
// Result: {"b":null,"c":null}
// Note: undefined properties are omitted entirely

Error 8: Bracket Mismatch

Mismatched or unclosed brackets are a common source of errors.

The Error

// ❌ INVALID - Missing closing brace
{
  "name": "Alice",
  "items": [1, 2, 3]

// ❌ INVALID - Wrong bracket type
{
  "items": [1, 2, 3}
]

The Fix

// βœ… VALID - Properly matched brackets
{
  "name": "Alice",
  "items": [1, 2, 3]
}

Counting Brackets

function validateBrackets(json) {
  let braces = 0;
  let brackets = 0;
  
  for (const char of json) {
    if (char === '{') braces++;
    if (char === '}') braces--;
    if (char === '[') brackets++;
    if (char === ']') brackets--;
  }
  
  if (braces !== 0) console.error('Mismatched curly braces');
  if (brackets !== 0) console.error('Mismatched square brackets');
  
  return braces === 0 && brackets === 0;
}

Best Tools for Fixing JSON Errors

1. Online JSON Validators

  • JSON Formatter Pro - Validates, formats, and shows error locations
  • JSONLint - Simple online validator
  • JSON Editor Online - Visual tree view with error highlighting

2. IDE Extensions

  • VS Code: Built-in JSON validation with error squiggles
  • JetBrains IDEs: Automatic syntax checking
  • Sublime Text: Pretty JSON package

3. Command Line Tools

# Validate JSON with jq
jq . data.json

# Python validation
python -m json.tool data.json

# Node.js
node -e "require('./data.json')"

4. Programmatic Validation

function validateJson(str) {
  try {
    JSON.parse(str);
    return { valid: true };
  } catch (error) {
    return {
      valid: false,
      error: error.message,
      position: error.message.match(/position (\d+)/)?.[1]
    };
  }
}

console.log(validateJson('{"name": "Alice"}')); 
// { valid: true }

console.log(validateJson('{"name": "Alice",}')); 
// { valid: false, error: "Unexpected token...", position: "18" }

Quick Reference: JSON Syntax Checklist

  • β˜‘οΈ All keys are double-quoted strings
  • β˜‘οΈ All string values use double quotes
  • β˜‘οΈ No trailing commas
  • β˜‘οΈ No comments
  • β˜‘οΈ Special characters are escaped
  • β˜‘οΈ All brackets are properly matched
  • β˜‘οΈ No undefined, NaN, or Infinity values
  • β˜‘οΈ UTF-8 encoding without BOM

Conclusion

JSON errors can be frustrating, but they're almost always easy to fix once you know what to look for. Remember these key points:

  1. Double quotes only - Never use single quotes
  2. No trailing commas - Remove that last comma
  3. No comments - JSON doesn't support them
  4. Escape special characters - Backslash, quotes, newlines
  5. Use validation tools - Let the computer find errors for you

Use our free JSON Formatter Pro tool to validate and fix your JSON instantly!

🏷️ Tags:
json debugging errors validation troubleshooting syntax tutorial

πŸ“š Related Articles