Best Practices 7 min read

JSON Formatting Best Practices

Write JSON that humans can actually read. Formatting tips, naming conventions, and tools that will make your data beautiful and maintainable.

#formatting #style #readability #conventions

TL;DR

  • Use 2-space indentation for human-readable JSON
  • camelCase for keys (myPropertyName)
  • Minify for production, pretty-print for development
  • Consistent ordering — alphabetical or logical grouping
  • Use formatters to enforce consistency

Why Formatting Matters

"It's just data, who cares how it looks?"

You will. At 3 AM. When you're debugging a 500-line config file and can't find that one misplaced comma. Formatting is a gift to your future self.

Well-formatted JSON is:

  • Easier to read — Find what you need quickly
  • Easier to debug — Spot errors at a glance
  • Easier to diff — Version control shows meaningful changes
  • Easier to maintain — Other developers will thank you

Indentation: The Great Debate

Two camps: 2 spaces vs 4 spaces. (Tabs people exist too, bless their hearts.)

Industry consensus: 2 spaces. Most major projects (npm, VS Code configs, Google's style guide) use 2 spaces. It's compact but readable.

2-space-indent.json
json
{
  "user": {
    "name": "Alice",
    "email": "alice@example.com",
    "settings": {
      "theme": "dark",
      "notifications": true
    }
  }
}

Compare with 4 spaces:

4-space-indent.json
json
{
    "user": {
        "name": "Alice",
        "email": "alice@example.com",
        "settings": {
            "theme": "dark",
            "notifications": true
        }
    }
}

Both work. Pick one for your project and stick with it. Consistency beats personal preference.

Key Naming Conventions

There are several conventions for naming JSON keys. Here's the breakdown:

camelCase (Recommended for JavaScript)

camelCase.json
json
{
  "firstName": "John",
  "lastName": "Doe",
  "emailAddress": "john@example.com",
  "phoneNumber": "+1-555-0100"
}

This is the standard in JavaScript ecosystems. It maps directly to JS object properties.

snake_case (Common in Python/Ruby APIs)

snake_case.json
json
{
  "first_name": "John",
  "last_name": "Doe",
  "email_address": "john@example.com",
  "phone_number": "+1-555-0100"
}

Python APIs often use this. It's also valid and widely used.

kebab-case (Avoid for JSON keys)

kebab-case.json
json
{
  "first-name": "John"
}

Don't use this. In JavaScript, you'd need bracket notation: obj["first-name"]. Annoying.

Pro tip: Match your JSON keys to your programming language's conventions. JavaScript projects → camelCase. Python APIs → snake_case.

Key Ordering

JSON objects are technically unordered. But for humans, order matters.

Option 1: Alphabetical

alphabetical.json
json
{
  "age": 28,
  "email": "john@example.com",
  "id": 1,
  "name": "John",
  "role": "admin"
}

Pros: Easy to find keys, consistent diffs. Cons: Related keys might be far apart.

Option 2: Logical Grouping

logical.json
json
{
  "id": 1,
  "name": "John",
  "email": "john@example.com",
  "age": 28,
  "role": "admin"
}

Pros: ID first (primary identifier), then personal info, then metadata. Cons: Requires agreement on what's "logical."

My recommendation: For config files, use logical grouping. For data interchange, alphabetical is safer.

Minified vs Pretty-Printed

Know when to use which:

Pretty-Printed (Development)

For humans: config files, debugging, documentation examples.

pretty.json
json
{
  "name": "my-app",
  "version": "1.0.0",
  "dependencies": {
    "express": "^4.18.2"
  }
}

Minified (Production)

For machines: API responses, data storage, network transfer.

minified.json
json
{"name":"my-app","version":"1.0.0","dependencies":{"express":"^4.18.2"}}

Minified JSON is ~30% smaller. For APIs serving millions of requests, that adds up to real bandwidth savings.

JavaScript Conversion

format-convert.js
javascript
const data = { name: "Alice", age: 25 };

// Pretty print
const pretty = JSON.stringify(data, null, 2);

// Minify
const mini = JSON.stringify(data);

// Pretty print existing JSON string
const formatted = JSON.stringify(JSON.parse(jsonString), null, 2);

Formatting Arrays

Short Arrays: Single Line

short-array.json
json
{
  "tags": ["javascript", "tutorial", "beginner"],
  "scores": [98, 87, 92]
}

Long Arrays: Multi-Line

long-array.json
json
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" },
    { "id": 3, "name": "Charlie" }
  ]
}

Array of Objects: One Per Line

array-objects.json
json
{
  "permissions": [
    {
      "resource": "users",
      "actions": ["read", "write"]
    },
    {
      "resource": "posts",
      "actions": ["read"]
    }
  ]
}

Rule of thumb: If an array fits on one line without scrolling, keep it there. Otherwise, expand it.

Null and Empty Values

Be consistent with how you handle missing data:

Option 1: Omit Missing Keys

omit-nulls.json
json
{
  "name": "Alice",
  "email": "alice@example.com"
}

The middleName key isn't present. Code must check if it exists.

Option 2: Include as Null

include-nulls.json
json
{
  "name": "Alice",
  "middleName": null,
  "email": "alice@example.com"
}

Explicit about what's missing. Easier for consumers to know what fields exist.

API design tip: Be consistent. If you sometimes omit nulls and sometimes include them, API consumers will be confused.

Date Formatting

JSON has no date type. Use ISO 8601 format:

dates.json
json
{
  "createdAt": "2024-11-24T10:30:00Z",
  "updatedAt": "2024-11-24T15:45:30.123Z",
  "birthDate": "1995-06-15"
}

Always include timezone for timestamps (the Z means UTC). Date-only fields (like birthDate) don't need time components.

Number Formatting

numbers.json
json
{
  "integer": 42,
  "float": 3.14159,
  "scientific": 1.23e10,
  "negative": -42,
  "zero": 0
}

Don't do this:

bad-numbers.json
json
{
  "price": "19.99",
  "count": "42",
  "available": "true"
}

Numbers and booleans should be their actual types, not strings. Stringly-typed data is a code smell.

Special Characters and Escaping

Some characters must be escaped in JSON strings:

Character Escape Sequence
Quotation mark\"
Backslash\\
Newline\n
Tab\t
Carriage return\r
escaping.json
json
{
  "quote": "She said \"Hello!\"",
  "path": "C:\\Users\\Documents",
  "multiline": "Line 1\nLine 2",
  "tab": "Column1\tColumn2"
}

Formatting Tools

Online Tools

  • JSON-parser.net — Our tool! Format, validate, and beautify JSON
  • VS Code built-in — Right-click → Format Document
  • Prettier — Supports JSON with configurable options

Command Line

cli-tools.sh
bash
# Python (built-in)
python -m json.tool input.json > formatted.json

# Node.js
cat input.json | npx json -o json-4

# jq (powerful JSON processor)
jq '.' input.json > formatted.json

Programmatic Formatting

programmatic.js
javascript
// JavaScript
const formatted = JSON.stringify(data, null, 2);

// With sorting keys
const sortedFormatted = JSON.stringify(data, Object.keys(data).sort(), 2);
Format JSON instantly! Use our JSON formatter to beautify, validate, and organize your JSON with one click.

Formatting Checklist

Before committing JSON files, check:

  • ✅ Consistent indentation (2 spaces recommended)
  • ✅ Consistent key naming (camelCase or snake_case)
  • ✅ No trailing commas
  • ✅ Numbers are numbers, not strings
  • ✅ Booleans are booleans, not strings
  • ✅ Dates use ISO 8601 format
  • ✅ No invalid characters or encoding issues
  • ✅ Valid JSON (run through a validator)

FAQ

Should I use single or double quotes?

Double quotes only. JSON doesn't support single quotes. Ever.

Can I add comments to JSON?

No. Standard JSON doesn't support comments. Use JSONC (JSON with Comments) if your tooling supports it, or switch to YAML for config files.

What about trailing commas?

Not allowed in JSON. Your parser will reject them. Use a linter or formatter to catch these.

About the Author

AT

Adam Tse

Founder & Lead Developer · 10+ years experience

Full-stack engineer with 10+ years of experience building developer tools and APIs. Previously worked on data infrastructure at scale, processing billions of JSON documents daily. Passionate about creating privacy-first tools that don't compromise on functionality.

JavaScript/TypeScript Web Performance Developer Tools Data Processing