← Back to JSON Tools

JSON Troubleshooting Guide 2025

Complete guide to debugging and fixing JSON errors. Learn to identify, understand, and resolve common JSON syntax errors, parsing issues, and validation problems with practical solutions.

🔧 Debug Guide ⚡ Quick Fixes 🛠️ Problem Solving 📚 Error Reference

📋 Table of Contents

🚨 Most Common JSON Errors

JSON errors fall into several categories. Understanding these patterns helps you quickly identify and fix issues in your JSON data.

HIGH

Syntax Errors

Incorrect JSON structure that prevents parsing: missing quotes, brackets, or commas in the wrong place.

  • Trailing commas
  • Single quotes instead of double
  • Missing quotes on keys
  • Unmatched brackets
HIGH

Encoding Issues

Character encoding problems that corrupt JSON data during transmission or storage.

  • UTF-8 BOM characters
  • Smart quotes from editors
  • Invalid Unicode sequences
  • Non-printable characters
MEDIUM

Data Type Errors

Invalid data types or format issues that violate JSON specification rules.

  • Undefined values
  • JavaScript functions
  • Date objects
  • Infinity/NaN numbers
MEDIUM

Structure Issues

Problems with JSON organization that affect parsing or validation against schemas.

  • Deeply nested objects
  • Circular references
  • Missing required fields
  • Inconsistent data structures
LOW

Formatting Problems

Issues that don't prevent parsing but affect readability and maintainability.

  • Poor indentation
  • Long lines
  • Inconsistent spacing
  • Missing line breaks
LOW

Performance Issues

JSON that technically works but causes performance problems in applications.

  • Extremely large objects
  • Redundant data
  • Deep nesting levels
  • Memory-intensive structures

🔧 Syntax Error Fixes

Syntax errors are the most common JSON problems. Here are the top issues and their solutions:

1. Trailing Commas

❌ Syntax Error: Trailing Comma

❌ INCORRECT (Trailing Comma)

{
  "name": "John",
  "age": 30,
}

✅ CORRECT (No Trailing Comma)

{
  "name": "John",
  "age": 30
}

Error Message: "Unexpected token '}' in JSON"

Solution: Remove the comma after the last property in objects and arrays.

2. Single Quotes vs Double Quotes

❌ Syntax Error: Single Quotes

❌ INCORRECT (Single Quotes)

{
  'name': 'John',
  'age': 30
}

✅ CORRECT (Double Quotes)

{
  "name": "John",
  "age": 30
}

Error Message: "Unexpected token ''' in JSON"

Solution: Always use double quotes for strings and property names in JSON.

3. Missing Quotes on Keys

❌ Syntax Error: Unquoted Keys

❌ INCORRECT (No Quotes on Keys)

{
  name: "John",
  age: 30,
  active: true
}

✅ CORRECT (Quoted Keys)

{
  "name": "John",
  "age": 30,
  "active": true
}

Error Message: "Unexpected token 'n' in JSON"

Solution: All property names must be enclosed in double quotes.

4. Unescaped Special Characters

❌ Syntax Error: Unescaped Characters

❌ INCORRECT (Unescaped Quotes)

{
  "message": "He said "Hello" to me"
}

✅ CORRECT (Escaped Quotes)

{
  "message": "He said \"Hello\" to me"
}

Common Escape Sequences:

  • \" - Double quote
  • \\ - Backslash
  • \n - Newline
  • \t - Tab
  • \r - Carriage return

5. Missing Brackets or Braces

❌ Syntax Error: Unmatched Brackets

❌ INCORRECT (Missing Closing Brace)

{
  "users": [
    {
      "name": "John",
      "age": 30
    // Missing closing brace
    {
      "name": "Jane",
      "age": 25
    }
  ]
// Missing closing brace

✅ CORRECT (Balanced Brackets)

{
  "users": [
    {
      "name": "John",
      "age": 30
    },
    {
      "name": "Jane",
      "age": 25
    }
  ]
}

Error Message: "Unexpected end of JSON input"

Solution: Ensure every opening bracket/brace has a matching closing bracket/brace.

🔍 Parsing & Validation Issues

Invalid Data Types

⚠️ Data Type Issues

JSON only supports specific data types. Here are common mistakes:

// ❌ INVALID JSON - These won't work
{
  "undefined": undefined,           // undefined is not valid JSON
  "function": function() { return 1; }, // functions not allowed
  "date": new Date(),                 // Date objects not valid
  "infinity": Infinity,              // Infinity not allowed
  "nan": NaN,                        // NaN not allowed
  "comment": /* comment */           // comments not allowed
}

// ✅ VALID JSON - Correct alternatives
{
  "undefined": null,              // Use null instead
  "result": 1,                   // Use the return value
  "date": "2025-01-14T10:30:00Z", // Use ISO date string
  "infinity": 1.7976931348623157e+308, // Use max number
  "nan": null,                   // Use null for missing values
  "description": "This is a comment"    // Use properties for notes
}

Encoding and Character Issues

ℹ️ Character Encoding Problems

Invisible characters and encoding issues can break JSON parsing:

Common Hidden Characters:

  • BOM (Byte Order Mark): Invisible character at start of file
  • Smart Quotes: Curly quotes from word processors
  • Non-breaking Spaces: Look like spaces but aren't
  • Zero-width Characters: Completely invisible but break parsing
// ❌ These look correct but contain hidden characters
{
  "name": "John",  // Smart quotes (curly quotes)
  "age": 30        // Non-breaking space instead of regular space
}

// ✅ Clean JSON with proper characters
{
  "name": "John",  // Straight quotes
  "age": 30         // Regular space
}

🛠️ Fixing Character Issues

  • Copy-paste JSON into a plain text editor
  • Check file encoding - should be UTF-8 without BOM
  • Replace smart quotes with straight quotes
  • Use "Show All Characters" in your editor
  • Save files as UTF-8 without BOM

🔍 Step-by-Step Debugging Methodology

  1. Copy the Error Message: Note the exact error message and line number if provided. This gives you the starting point for debugging.
  2. Use a JSON Validator: Paste your JSON into a validator tool to identify syntax errors immediately. Most validators highlight the exact location of problems.
  3. Check Basic Syntax: Verify that all strings use double quotes, property names are quoted, and there are no trailing commas.
  4. Balance Brackets and Braces: Count opening and closing brackets. Use an editor that highlights matching brackets to spot imbalances.
  5. Look for Invisible Characters: If JSON looks correct but fails validation, check for hidden characters like smart quotes or BOM.
  6. Validate Data Types: Ensure all values are valid JSON types (string, number, boolean, null, object, array). No undefined, functions, or comments.
  7. Test in Sections: For large JSON files, validate smaller sections to isolate the problematic area.
  8. Use Pretty Printing: Format the JSON with proper indentation to make structure issues more visible.
  9. Compare with Working Examples: If possible, compare your JSON structure with known working examples.
  10. Re-validate After Each Fix: Fix one error at a time and re-validate to ensure you haven't introduced new issues.

💬 Common Error Messages & Solutions

❌ "Unexpected token" errors

Error: "Unexpected token '}' in JSON at position X"

Cause: Trailing comma before closing brace

Solution: Remove the comma after the last property

Error: "Unexpected token ''' in JSON at position X"

Cause: Single quotes instead of double quotes

Solution: Replace all single quotes with double quotes

Error: "Unexpected token 'u' in JSON at position X"

Cause: undefined value in JSON

Solution: Replace undefined with null or remove the property

❌ "Unexpected end of JSON input"

Cause: Incomplete JSON - missing closing brackets, braces, or quotes

Common scenarios:

  • Truncated JSON during copy/paste
  • Network timeout cutting off JSON response
  • Missing closing bracket at end of file
  • Unclosed string (missing closing quote)

Solution: Check that all opening brackets have matching closing brackets

❌ "JSON.parse: unexpected character"

Cause: Invalid character in JSON (often hidden/invisible characters)

Solution:

  1. Copy JSON to plain text editor
  2. Enable "Show All Characters" mode
  3. Look for unusual characters or spacing
  4. Re-type the problematic section
❌ "Unexpected number in JSON"

Cause: Invalid number format

Examples of invalid numbers:

// ❌ Invalid number formats
{
  "hex": 0xFF,          // Hex not allowed
  "octal": 0755,        // Octal not allowed  
  "infinity": Infinity,  // Infinity not allowed
  "nan": NaN,           // NaN not allowed
  "leading": 01.5       // Leading zeros not allowed
}

// ✅ Valid number formats
{
  "hex": 255,          // Use decimal
  "octal": 493,        // Use decimal equivalent
  "infinity": null,    // Use null or very large number
  "nan": null,         // Use null for missing values
  "decimal": 1.5       // No leading zeros
}

🛡️ Error Prevention Best Practices

🔧 Development Practices

  • Use a JSON linter: Configure your editor to validate JSON as you type
  • Pretty print JSON: Always format JSON with proper indentation for readability
  • Validate before saving: Use JSON.parse() to test validity before storing JSON
  • Use JSON generators: Prefer programmatic JSON generation over manual editing
  • Version control: Track JSON schema changes and validate against test data

📝 Writing Clean JSON

  • Consistent formatting: Use 2 or 4 spaces for indentation consistently
  • Meaningful property names: Use clear, descriptive keys
  • Logical structure: Group related properties together
  • Avoid deep nesting: Keep nesting levels reasonable (< 5 levels)
  • Document complex structures: Add comments in separate documentation

⚠️ Common Pitfalls to Avoid

  • Copying JSON from word processors (introduces smart quotes)
  • Manually editing large JSON files (use tools instead)
  • Assuming JavaScript object syntax works in JSON
  • Not testing JSON after manual modifications
  • Ignoring character encoding when transferring JSON

Automated Validation

// JavaScript: Always wrap JSON.parse in try-catch
function safeJSONParse(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error('JSON parsing failed:', error.message);
    console.error('Error at position:', error.message.match(/position (\d+)/)?.[1]);
    return null;
  }
}

// Python: Use json module with error handling
import json

def safe_json_parse(json_string):
    try:
        return json.loads(json_string)
    except json.JSONDecodeError as e:
        print(f"JSON parsing failed: {e.msg}")
        print(f"Error at line {e.lineno}, column {e.colno}")
        return None

🛠️ Essential JSON Debugging Tools

Online Validator

Better JSON Viewer

Instant JSON validation with detailed error messages, syntax highlighting, and formatting tools. Works completely offline.

Browser Tool

Developer Console

Use JSON.parse() in browser console for quick validation. Shows exact error location and clear error messages.

Editor Plugin

VS Code JSON Extension

Real-time JSON validation, syntax highlighting, and auto-completion. Shows errors as you type.

Command Line

jq Processor

Command-line JSON processor that validates and formats JSON files. Great for batch validation and processing.

Online Tool

JSON Formatter

Online tools that format and validate JSON, showing clear error messages and line numbers for quick debugging.

Programming

Language Validators

Built-in JSON parsers in programming languages (JSON.parse, json.loads) with try-catch error handling.

🎯 Tool Selection Tips

  • Quick fixes: Use online validators for immediate error detection
  • Development: Configure editor plugins for real-time validation
  • Large files: Use command-line tools for batch processing
  • Production: Implement programmatic validation with proper error handling
  • Privacy: Use offline tools for sensitive JSON data

🚀 Advanced Troubleshooting Techniques

Debugging Large JSON Files

Binary Search Debugging

  1. Split the file: Divide large JSON into smaller sections
  2. Test each half: Validate each section to find which contains the error
  3. Subdivide further: Continue splitting the problematic section
  4. Isolate the error: Narrow down to the exact problematic line
  5. Fix and reassemble: Correct the error and validate the complete file

Handling API Response Errors

// Robust API response handling
async function fetchAndParseJSON(url) {
  try {
    const response = await fetch(url);
    
    // Check if response is OK
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    // Check content type
    const contentType = response.headers.get('content-type');
    if (!contentType?.includes('application/json')) {
      throw new Error('Response is not JSON');
    }
    
    // Get response text first
    const text = await response.text();
    
    // Log for debugging if needed
    console.log('Raw response:', text.substring(0, 200) + '...');
    
    // Parse JSON with error handling
    return JSON.parse(text);
    
  } catch (error) {
    if (error instanceof SyntaxError) {
      console.error('JSON parsing error:', error.message);
      console.error('Check the API response format');
    } else {
      console.error('Network or other error:', error.message);
    }
    throw error;
  }
}

Schema Validation Debugging

ℹ️ Schema Validation Issues

When JSON is syntactically correct but fails schema validation:

Common Schema Issues:

  • Missing required fields: Check that all required properties are present
  • Wrong data types: Verify string vs number vs boolean types
  • Invalid enum values: Ensure values match allowed options exactly
  • Format violations: Check email, date, URI formats
  • Range violations: Verify min/max length, value constraints
// Schema validation debugging
function validateWithDetailedErrors(data, schema) {
  const ajv = new Ajv({ allErrors: true });
  const validate = ajv.compile(schema);
  const valid = validate(data);
  
  if (!valid) {
    console.log('Validation errors:');
    validate.errors.forEach(error => {
      console.log(`- ${error.instancePath}: ${error.message}`);
      console.log(`  Data: ${JSON.stringify(error.data)}`);
      console.log(`  Schema: ${JSON.stringify(error.schema)}`);
    });
  }
  
  return valid;
}

🚨 When JSON Seems Correct But Still Fails

If your JSON looks perfect but still doesn't work:

  1. Check for invisible characters: Paste into a hex editor or use cat -A (Linux/Mac)
  2. Verify encoding: Ensure UTF-8 without BOM
  3. Test minimal examples: Start with the simplest possible JSON and add complexity
  4. Compare binary: Use diff tools to compare with known working JSON
  5. Check platform differences: Windows vs Unix line endings can cause issues

🔧 Debug Your JSON Now

Use our comprehensive JSON tools to validate, format, and debug your JSON data. Get instant error detection and clear solutions.

Validate JSON → Validation Guide Schema Tutorial

Related Guides

Error Types

  • Syntax Errors
  • Parsing Issues
  • Validation Problems
  • Encoding Issues

Quick Fixes

  • Remove Trailing Commas
  • Fix Quote Types
  • Balance Brackets
  • Escape Special Characters

Your complete guide to debugging and fixing JSON errors quickly and effectively.

Last updated: January 14, 2025 • © 2025 Better JSON Viewer