UtilopiaUtilopia

Command Palette

Search for a command to run...

JSON Formatting Best Practices for Developers

JSON Formatting Best Practices for Developers

March 4, 2026·10 min readjsondeveloper toolsbest practicesweb development

A single misplaced comma in a JSON file can break an entire deployment. If you've spent 20 minutes hunting for a syntax error only to find a trailing comma on line 847, you already know that JSON formatting is not just about aesthetics — it directly affects your productivity and your team's ability to ship code.

JSON (JavaScript Object Notation) has become the lingua franca of data exchange on the web. APIs return it, config files use it, databases store it. Yet most developers never think twice about how they format it. That's a mistake. Consistent JSON formatting reduces bugs, speeds up code reviews, and makes debugging significantly faster.

Here's everything you need to know about formatting JSON the right way.

Why JSON Formatting Matters More Than You Think

Messy JSON is hard to read. Hard-to-read JSON means slower debugging. Slower debugging means missed deadlines. The chain reaction is real.

Consider a 200-line JSON response from an API. If it arrives minified — one giant line of text — good luck finding the nested object you need. But format it with proper indentation, and suddenly the structure jumps out at you. You can trace parent-child relationships, spot missing fields, and verify data types in seconds.

Beyond readability, consistent formatting matters for version control. When two developers format the same JSON file differently, git diff becomes a nightmare. Every line shows as changed even if the actual data hasn't moved. This noise buries real changes and makes code reviews painful.

Teams that agree on JSON formatting conventions avoid these problems entirely. The investment is small — the payoff compounds over every commit.

Indentation: 2 Spaces vs 4 Spaces vs Tabs

This debate has strong opinions on all sides. Here's the practical breakdown:

Style Used By Pros Cons
2 spaces Google, Airbnb, npm/package.json Compact, less horizontal scrolling Can be harder to scan visually
4 spaces Python community, many Java projects Clear visual hierarchy Deep nesting pushes code far right
Tabs Go community (for source code) Configurable display width Rare in JSON specifically

For JSON specifically, 2 spaces is the most common standard. The JSON output of JSON.stringify(data, null, 2) uses 2 spaces by default in most examples and tutorials. npm's package.json uses 2 spaces. Most linters default to 2 spaces for JSON files.

That said, 4 spaces works perfectly fine if your team prefers it. The real rule is: pick one and enforce it everywhere. A codebase that mixes 2-space and 4-space JSON files is worse than either choice alone.

If you need to quickly reformat JSON between styles, a JSON Formatter lets you switch between 2-space and 4-space indentation instantly — paste your JSON, pick your indent size, and copy the result.

Practical recommendation

Use 2 spaces for JSON. Configure your editor's .editorconfig or .prettierrc to enforce it:

{
  "overrides": [
    {
      "files": "*.json",
      "options": {
        "tabWidth": 2
      }
    }
  ]
}

Key Ordering and Naming Conventions

JSON doesn't care about key order — {"b": 1, "a": 2} and {"a": 2, "b": 1} are semantically identical. But humans care. A lot.

Alphabetical key ordering is the safest default. It eliminates debates about "logical" ordering (which is subjective), makes keys easy to find in large objects, and produces cleaner diffs since new keys slot into predictable positions.

For naming conventions, the JSON ecosystem is split:

Convention Common In Example
camelCase JavaScript/TypeScript APIs, most REST APIs firstName, createdAt
snake_case Python APIs, Ruby on Rails, PostgreSQL first_name, created_at
kebab-case Rare in JSON (common in URLs and CSS) first-name
PascalCase .NET APIs, C# conventions FirstName, CreatedAt

Match your API's language conventions. If your backend is Node.js, use camelCase. If it's Python/Django, snake_case is natural. Consistency within a single API matters far more than which convention you choose.

One common anti-pattern: mixing conventions within the same response. This usually happens when an API aggregates data from multiple services. If you control the API, normalize the keys at the boundary. Your consumers will thank you.

Common JSON Mistakes and How to Fix Them

JSON's syntax is deceptively simple, but it's also strict. Here are the mistakes that catch developers most often:

Trailing commas

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

That comma after 30 is invalid JSON. JavaScript allows trailing commas in objects and arrays, so developers who write JSON by hand often include them out of habit. Every JSON parser will reject this.

Comments

{
  // This is not valid
  "name": "Alice"
}

JSON does not support comments. Period. If you need commented configuration files, consider JSONC (JSON with Comments, supported by VS Code), JSON5, or YAML. For pure data exchange, strip the comments.

Single quotes

{
  'name': 'Alice'
}

JSON requires double quotes for both keys and string values. Single quotes will fail parsing. This trips up Python developers especially, since Python's json.dumps() correctly uses double quotes but str() on a dict uses single quotes.

Unquoted keys

{
  name: "Alice"
}

Unlike JavaScript object literals, JSON keys must be quoted. Always.

Number edge cases

{
  "value": .5,
  "hex": 0xFF,
  "infinity": Infinity
}

JSON numbers must have a leading digit (use 0.5, not .5). Hexadecimal literals, Infinity, NaN, and undefined are all invalid in JSON.

A quick way to catch all of these: paste your JSON into a JSON Formatter. If it can't parse the input, you've got a syntax error — and most formatters will tell you exactly where.

Minified vs Pretty-Printed: When to Use Each

Both formats have their place. Using the wrong one in the wrong context wastes either bandwidth or developer time.

When to minify

  • API responses in production — Removing whitespace from a large JSON response can reduce payload size by 10-30%. For high-traffic APIs, that's meaningful bandwidth savings.
  • Data stored in databases — If you're storing JSON blobs, minified format uses less disk space.
  • Message queues and event streams — Kafka, RabbitMQ, and similar systems process millions of messages. Smaller messages mean higher throughput.

When to pretty-print

  • Configuration filespackage.json, tsconfig.json, .eslintrc.json — these are read and edited by humans. Always pretty-print.
  • Debugging and logging — When inspecting API responses during development, pretty-printed JSON is dramatically easier to read.
  • Documentation and examples — Any JSON shown to other developers should be formatted for readability.
  • Version control — Pretty-printed JSON produces meaningful line-by-line diffs. Minified JSON shows the entire file as a single changed line.

The size difference in practice

Here's a real-world comparison using a typical API response:

Format Size Reduction
Pretty-printed (2 spaces) 4,280 bytes
Minified 3,120 bytes 27% smaller
Minified + gzip 890 bytes 79% smaller

Notice that gzip compression — which most web servers apply automatically — narrows the gap significantly. The difference between gzipped pretty-printed and gzipped minified JSON is often negligible. So if your server uses gzip (and it should), the formatting choice matters less for transfer size than you might think.

The takeaway: minify for production APIs and data storage, pretty-print for everything humans touch.

Tools and Workflows for JSON Formatting

Manual formatting is error-prone and slow. Automate it.

Editor integration

Most modern editors can format JSON on save:

  • VS Code: Install the Prettier extension, enable "Format on Save", and configure JSON formatting in settings.
  • JetBrains IDEs: Built-in JSON formatter via Code > Reformat Code (Cmd+Alt+L / Ctrl+Alt+L).
  • Vim/Neovim: Use :%!python3 -m json.tool for quick formatting or integrate with prettier via a plugin.

Command-line tools

For CI/CD pipelines and scripts:

# Python (built-in)
python3 -m json.tool input.json > formatted.json

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

# Node.js one-liner
node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync(0,'utf8')),null,2))" < input.json

jq deserves special mention. It's not just a formatter — it can filter, transform, and query JSON data. If you work with JSON regularly and haven't learned jq, you're missing out.

Online formatters

Sometimes you need to quickly format a JSON snippet from Slack, an email, or a log file. Opening your editor, creating a temp file, and formatting it there is overkill. An online JSON Formatter handles this in seconds — paste, format, copy. No setup, no file cleanup.

Look for a formatter that also supports minification. When you need to compress a pretty-printed config into a single line for an environment variable or CLI argument, having both options in one place saves time.

Pre-commit hooks

To enforce formatting across your team, add a pre-commit hook:

{
  "hooks": {
    "pre-commit": "prettier --check '**/*.json'"
  }
}

This prevents unformatted JSON from ever reaching your repository. No more formatting-only commits cluttering your git history.

JSON in APIs: Request and Response Conventions

Beyond formatting, a few API-specific conventions are worth following.

Consistent response envelopes

Pick a response structure and stick with it:

{
  "data": { ... },
  "meta": {
    "page": 1,
    "totalPages": 10
  }
}

Or for errors:

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Email is required",
    "field": "email"
  }
}

Null vs absent keys

Should missing data be represented as null or by omitting the key entirely? Both approaches work, but be consistent. Explicitly including null values makes the API contract clearer — consumers know exactly which fields exist. Omitting keys produces smaller payloads but requires consumers to handle missing properties.

Most modern APIs lean toward including null for known fields and omitting keys only for truly optional or dynamic properties.

Date formats

Use ISO 8601. Always.

{
  "createdAt": "2026-03-04T14:30:00Z"
}

Not Unix timestamps (hard to read), not "March 4, 2026" (locale-dependent), not "03/04/2026" (ambiguous between US and international formats). ISO 8601 is unambiguous, sortable, and universally supported.

Frequently Asked Questions

What is the maximum size limit for a JSON file?

JSON itself has no size limit — the constraint comes from the parser or system processing it. Most programming languages can handle JSON files of several hundred megabytes. However, browser-based JSON.parse() may struggle with files over 500 MB. For very large datasets, consider streaming parsers like JSONStream (Node.js) or ijson (Python) that process data incrementally without loading the entire file into memory.

Should I use JSON or YAML for configuration files?

JSON is better for machine-generated configs and strict data exchange. YAML is better for human-edited configs because it supports comments, multiline strings, and anchors. If your config file will be frequently edited by hand, YAML is usually the better choice. If it's generated or consumed primarily by code, stick with JSON for its stricter parsing and wider tooling support.

How do I validate JSON against a schema?

Use JSON Schema — a vocabulary that lets you define the structure, types, and constraints of your JSON data. Tools like ajv (JavaScript), jsonschema (Python), and online validators let you check any JSON document against a schema. This is especially valuable for API contracts, ensuring that both producers and consumers agree on the data format.

Is JSON faster than XML for data exchange?

JSON is generally smaller and faster to parse than XML for equivalent data. JSON parsing is native to JavaScript and most modern languages, while XML requires dedicated parsers. A typical JSON payload is 30-50% smaller than its XML equivalent. That said, XML has advantages for document-oriented data with mixed content (like HTML). For APIs and data exchange, JSON is the clear winner in both performance and developer experience.

Can JSON contain binary data?

Not directly. JSON is a text format and can only represent strings, numbers, booleans, null, arrays, and objects. To include binary data (images, files, etc.), you need to encode it as a string — typically using Base64 encoding. The trade-off is that Base64 encoding increases the data size by about 33%. For large binary payloads, consider sending the binary data separately (e.g., multipart form data) and referencing it in your JSON with a URL or identifier.