JSON Formatting Best Practices for Developers
JSONBest PracticesTips

JSON Formatting Best Practices for Developers

Why JSON Formatting Matters

Raw JSON returned from APIs is usually minified — stripped of all whitespace to save bandwidth. While this is great for production, it makes debugging a nightmare. A single misplaced comma or bracket can be invisible in a wall of text. Every developer who has spent 20 minutes hunting a missing closing brace knows exactly what this feels like.

Proper formatting makes the structure of your data immediately visible, reduces the time spent debugging, and makes code reviews much cleaner. When your entire team follows the same formatting conventions, git diffs become meaningful rather than noisy. A one-line change should produce a one-line diff — not a page-long reformatting cascade.

Beyond the human benefits, consistent JSON formatting also aids tooling. Linters, formatters, and diff tools all work better when they don't have to guess about your style preferences. Setting formatting conventions early in a project is one of the cheapest improvements you can make to developer experience.

Indentation: 2 Spaces vs 4 Spaces

The most common debate in JSON formatting is indentation size. Here is the breakdown:

  • 2 spaces — used by most modern style guides (Prettier, ESLint defaults). Compact enough for deeply nested objects without horizontal scrolling.
  • 4 spaces — preferred by developers coming from Python or Java backgrounds. More readable for shallow structures where nesting is rare.
  • Tabs — avoid for JSON. The JSON spec technically allows it, but tabs cause inconsistency across editors because different editors render tabs at different widths.

Our recommendation: use 2 spaces for API responses and config files, 4 spaces for documentation and human-readable exports. The most important thing is consistency within a project — pick one and enforce it with Prettier.

When working across teams with different editors, always commit a .editorconfig file alongside your .prettierrc. This ensures that even developers who do not run Prettier see consistent formatting in their editor.

Key Ordering

JSON objects do not guarantee key order per the spec, but in practice, most JavaScript engines (V8, SpiderMonkey) preserve insertion order for non-integer keys. For readability and cleaner diffs in version control, adopt a consistent ordering convention:

  • Put identifier fields first (id, type, name)
  • Group related fields together (all address fields together, all payment fields together)
  • Put metadata last (createdAt, updatedAt, deletedAt)

Alphabetical sorting is another valid approach — it makes finding keys predictable and reduces merge conflicts when multiple developers add fields to the same object. Tools like sort-keys in ESLint or Prettier plugins can enforce this automatically.

For API responses specifically, put the most frequently accessed fields first. When developers are reading raw JSON in a terminal or log viewer, they should see the most important information immediately — usually the ID and status — without scrolling.

Handling Nested Objects

Deep nesting is a red flag in API design. If you find yourself formatting JSON that is 6 or more levels deep, it is a strong signal to reconsider your data model. Over-nested JSON is harder to traverse in code, harder to index in databases, and harder to read in any format.

{
  "user": {
    "profile": {
      "address": {
        "city": "Jakarta",
        "country": "ID"
      }
    }
  }
}

Consider flattening this to:

{
  "userId": "abc123",
  "profileCity": "Jakarta",
  "profileCountry": "ID"
}

Or use dot-notation keys for truly flat storage, or separate the concerns into different API endpoints entirely. Each level of nesting should clearly represent a meaningful relationship, not just be a wrapper object created out of habit.

Trailing Commas

Standard JSON does not allow trailing commas. This is a common gotcha when copying code from JavaScript (which allows them in objects and arrays since ES5) into a JSON file. A JSON parser will throw a syntax error on trailing commas — and the error message is often unhelpful.

The safest habit: always run your JSON through a formatter or validator before committing it. Tools like jq, the browser's JSON.parse(), or our online JSON Formatter will catch trailing commas instantly.

Comments in JSON

JSON does not support comments — this was an intentional design decision by Douglas Crockford, who wanted to keep the format as simple and interoperable as possible. But in practice, developers often need to annotate config files.

Your options:

  • JSONC (JSON with Comments) — supported by VS Code, TypeScript's tsconfig.json, and many tools. Syntax is identical to JSON with // and /* */ comments added.
  • _comment keys — adding a key like "_comment": "This field controls rate limiting" works but is hacky and gets serialized into payloads.
  • Separate documentation — for shared API schemas, maintain a README or OpenAPI spec alongside the JSON files.

Null vs Omitting the Key

A common source of inconsistency: when a value is absent, should you include the key with a null value, or omit the key entirely? Both patterns exist in the wild, but pick one and stick to it.

  • Include null: Makes the schema explicit. Consumers know the field exists; it just has no value. Easier to destructure safely in JavaScript.
  • Omit the key: Smaller payload. But consumers must use optional chaining (obj?.field) everywhere, or they risk runtime errors.

For public APIs, prefer including null values so that your schema is self-documenting in the response itself.

Number Precision

JSON numbers are IEEE 754 doubles, which means integers larger than 2^53 - 1 (9007199254740991) cannot be represented precisely. For large IDs (common in distributed systems using Snowflake IDs or UUIDs encoded as integers), serialize them as strings instead of numbers.

{
  "orderId": "9007199254740993",   ✓ safe as string
  "orderId": 9007199254740993      ✗ may lose precision in JS
}

Tools for Enforcing Consistency

Use PureFormatter's JSON Formatter to instantly clean and validate any JSON. For projects, set up Prettier with a .prettierrc to enforce formatting automatically on save and in CI. Add a pre-commit hook with husky + lint-staged to prevent unformatted JSON from ever hitting your main branch.

For API development, use a tool like Insomnia or Postman's built-in formatter during testing, so you always work with readable JSON — not minified blobs.

Fredy
Written by
Fredy
Senior Developer & Technical Writer

Fredy is a full-stack developer with 8+ years of experience building web applications. He writes about developer tools, best practices, and the craft of clean code.