FlyingFish Space
Back to Guides

JSON Formatting and Validation: A Complete Guide

AD
Developer Tool

JSON Pipeline β€” A practical toolkit for working with JSON.

Clean, repair, transform and validate JSON without adding unnecessary friction.

JSON Clean AI Repair Transform Schema
Explore JSON Pipeline β†’
Quick Reference

Most Common JSON Errors:
1. Trailing commas (40% of errors)
2. Single quotes instead of double quotes
3. Unescaped quotes inside strings
4. Missing commas between items
5. Hidden UTF-8 BOM characters

JSON is everywhere. Whether you're building APIs, configuring applications, or exchanging data between services, JSON is the glue that holds modern software together. And yet, despite its simplicity, JSON is also one of the most common sources of frustrating bugs.

A missing quote, an extra comma, or a stray invisible character can break an entire workflow β€” and the error messages are often cryptic enough to make you question your life choices.

This guide breaks down the problem, explains why JSON errors happen so frequently, and gives you a practical, reliable approach to formatting and validating JSON correctly every time.

1. The Problem: "My JSON Looks Fine… Why Won't It Parse?"

If you've ever stared at a JSON file that looks perfectly valid but still refuses to parse, you're not alone. Developers run into JSON issues constantly:

  • A tool or API returns "Invalid JSON" with no further explanation
  • A JSON file works in one environment but fails in another
  • A trailing comma or missing quote breaks the entire payload
  • JSON copied from a document contains hidden characters
  • Formatting is inconsistent, making the file hard to debug

Real-World Error Messages

// Error 1: The Cryptic One
"SyntaxError: Unexpected token } in JSON at position 347"
// Translation: Extra comma before position 347

// Error 2: The Invisible Character
"SyntaxError: Unexpected token ο»Ώ in JSON at position 0"
// Translation: UTF-8 BOM at file start

// Error 3: The Quote Nightmare
"SyntaxError: Unexpected token ' in JSON at position 12"
// Translation: Single quotes instead of double quotes

2. The Cause: Strict Syntax Rules

2.1 JSON Is Not JavaScript

JSON has strict rules. Things allowed in JavaScript objects are NOT allowed in JSON:

❌ No Single Quotes

// JavaScript (works)
const obj = { 'name': 'Alice' };

// JSON (fails)
{ 'name': 'Alice' }

// JSON (correct)
{ "name": "Alice" }

❌ No Trailing Commas

// JavaScript (works)
const obj = { name: "Alice", };

// JSON (fails)
{ "name": "Alice", }

// JSON (correct)
{ "name": "Alice" }

❌ No Comments

// JSON (fails)
{ // comment
  "name": "Alice"
}

// JSON (correct)
{ "name": "Alice" }

JSON vs JavaScript Comparison

FeatureJavaScriptJSON
QuotesSingle or doubleDouble only
KeysCan be unquotedMust be quoted
Trailing commasAllowedNot allowed
CommentsAllowedNot allowed
undefinedAllowedUse null

3. Common Structural Mistakes

Missing Commas

// ❌ Wrong
{
  "name": "Alice"
  "age": 30
}

// βœ… Correct
{
  "name": "Alice",
  "age": 30
}

Unescaped Quotes

// ❌ Wrong
{ "msg": "She said "hello"" }

// βœ… Correct
{ "msg": "She said \"hello\"" }

4. The Solution: Validation Workflow

Step 1: Format JSON

// JavaScript
function formatJSON(str) {
  const obj = JSON.parse(str);
  return JSON.stringify(obj, null, 2);
}

// Python
import json
def format_json(s):
    obj = json.loads(s)
    return json.dumps(obj, indent=2)

Step 2: Validate JSON

// JavaScript
function validateJSON(str) {
  try {
    JSON.parse(str);
    return { valid: true };
  } catch (e) {
    return { 
      valid: false, 
      error: e.message 
    };
  }
}

Step 3: Use Checklist

  • ☐ All keys in double quotes?
  • ☐ All strings in double quotes?
  • ☐ No trailing commas?
  • ☐ All braces/brackets closed?
  • ☐ Quotes inside strings escaped?
  • ☐ File saved as UTF-8 without BOM?

5. Best Practices

Always Validate API Responses

async function fetchData() {
  const response = await fetch('/api/data');
  const text = await response.text();
  
  try {
    const data = JSON.parse(text);
    return data;
  } catch (e) {
    console.error('Invalid JSON:', e);
    throw e;
  }
}

Use Prettier for Formatting

// .prettierrc
{
  "tabWidth": 2,
  "useTabs": false,
  "trailingComma": "none"
}

6. Tools and Resources

ToolPurpose
JSONLintOnline validator
jqCommand-line tool
PrettierAuto-formatter
VS CodeBuilt-in validation

Conclusion

JSON errors are frustrating but predictable. With the right workflow:

  1. Format your JSON properly
  2. Validate before using
  3. Use automated tools
  4. Follow the checklist

JSON doesn't have to be painful. Master these fundamentals and eliminate 95% of JSON-related bugs.

πŸ“– You Might Also Like