JSON Formatting Best Practices for Developers

JSON (JavaScript Object Notation) is the universal data interchange format. But messy JSON is hard to debug. This guide covers formatting, validation, and best practices.

Pretty-Print JSON

JavaScript

const obj = {name:"John",age:30,city:"NYC"};

// 2-space indentation
console.log(JSON.stringify(obj, null, 2));

// 4-space indentation  
console.log(JSON.stringify(obj, null, 4));

// Output:
{
  "name": "John",
  "age": 30,
  "city": "NYC"
}

Command Line (jq)

# Pretty-print
echo '{"name":"John","age":30}' | jq .

# Minify
jq -c . input.json

JSON Validation

// Valid JSON
{
  "name": "John",
  "active": true,
  "score": 95.5
}

// Invalid JSON (common mistakes)
{
  name: "John",        // ❌ Keys must be quoted
  'name': "John",      // ❌ Must use double quotes
  "trailing": "comma", // ❌ No trailing commas
}

JSON Best Practices

🎨 Format JSON Instantly

Use our free JSON Formatter to beautify, validate, minify, and sort JSON with one click.

Format JSON →

Common Patterns

API Response

{
  "status": "success",
  "data": {
    "users": [
      {"id": 1, "name": "John"},
      {"id": 2, "name": "Jane"}
    ]
  },
  "meta": {
    "total": 2,
    "page": 1
  }
}

Configuration File

{
  "server": {
    "port": 3000,
    "host": "localhost"
  },
  "database": {
    "connection": "postgresql://localhost/db"
  }
}

← Back to Blog