JSON Formatting Best Practices for Developers

JSON (JavaScript Object Notation) has become the universal language of data exchange on the web. Whether you are building REST APIs, configuring applications, or debugging webhooks, you will encounter JSON daily. Yet poorly formatted JSON is one of the most common sources of bugs, merge conflicts, and wasted debugging time.

This guide covers the formatting conventions, common pitfalls, and validation strategies that will save you hours of frustration. If you need to format or validate JSON right now, try our JSON Formatter & Validator — it runs entirely in your browser.

What JSON Is and Why Formatting Matters

JSON is a lightweight, text-based data format that uses key-value pairs and ordered lists to represent structured data. It was derived from JavaScript but is language-independent — every modern programming language can parse and generate JSON.

A JSON document is either an object (wrapped in {}) or an array (wrapped in []). Values can be strings, numbers, booleans, null, objects, or arrays. That simplicity is its strength — and also why formatting matters. Without consistent formatting, even a small JSON document becomes difficult to read, review, and debug.

Consider this minified API response:

{"users":[{"id":1,"name":"Alice","roles":["admin","editor"],"settings":{"theme":"dark","notifications":true}},{"id":2,"name":"Bob","roles":["viewer"],"settings":{"theme":"light","notifications":false}}]}

Now compare the same data, properly formatted:

{
  "users": [
    {
      "id": 1,
      "name": "Alice",
      "roles": ["admin", "editor"],
      "settings": {
        "theme": "dark",
        "notifications": true
      }
    },
    {
      "id": 2,
      "name": "Bob",
      "roles": ["viewer"],
      "settings": {
        "theme": "light",
        "notifications": false
      }
    }
  ]
}

The structure, hierarchy, and relationships are immediately clear. That is the power of proper formatting.

JSON Formatting Conventions

Indentation: 2 Spaces vs. 4 Spaces vs. Tabs

The JSON specification does not mandate any particular indentation. In practice, the three most common choices are:

  • 2 spaces — the most popular choice in JavaScript/TypeScript ecosystems. It is the default for Prettier, many npm packages, and Google's style guide.
  • 4 spaces — common in Java, Python, and .NET projects. Visual Studio and IntelliJ default to this for JSON.
  • Tabs — less common for JSON but used in some codebases for accessibility (tab width is configurable per editor).

The right choice is whichever one your team already uses. Consistency is more important than the specific number. In JavaScript, JSON.stringify(data, null, 2) produces 2-space indented output.

Key Naming: camelCase vs. snake_case

JSON keys should follow a consistent naming convention:

  • camelCase (userId, createdAt, firstName) — standard in JavaScript/TypeScript APIs, Google's JSON style guide, and most frontend frameworks.
  • snake_case (user_id, created_at, first_name) — standard in Python (Django, Flask) and Ruby (Rails) APIs.
  • kebab-case (user-id) — avoid for JSON keys as it requires bracket notation in JavaScript (obj["user-id"] instead of obj.userId).

If you are building a new API, camelCase is the safest default since JSON originates from JavaScript. Whatever you choose, document it in your API style guide and enforce it with linting.

Minified vs. Pretty-Printed JSON

Both formats have their place. The key is knowing when to use each:

Use Minified JSON For:

  • API responses — removes all unnecessary whitespace to reduce payload size. A 100KB pretty-printed response might be only 60-70KB minified.
  • Network transmission — smaller payloads mean faster transfers, especially on mobile networks.
  • Database storage — saves disk space and I/O when storing JSON blobs.
  • Log files — one JSON object per line (JSONL format) makes log parsing easier.

Use Pretty-Printed JSON For:

  • Configuration filespackage.json, tsconfig.json, .eslintrc.json should always be human-readable.
  • Debugging — when inspecting API responses or webhook payloads, format them first.
  • Documentation — example payloads in docs should always be pretty-printed.
  • Version control — pretty-printed JSON produces meaningful diffs in git. Minified JSON shows the entire file as one changed line.

Most web servers can be configured to send minified JSON in production while developers use browser extensions or tools like our JSON Formatter to pretty-print responses for debugging.

Common JSON Errors and How to Fix Them

These five mistakes cause the vast majority of JSON parsing failures:

1. Trailing Commas

Unlike JavaScript, JSON does not allow trailing commas. This is invalid:

{ "name": "Alice", "age": 30, }  // INVALID - trailing comma

Remove the comma after the last item: { "name": "Alice", "age": 30 }

2. Single Quotes

JSON requires double quotes for strings. Single quotes are a syntax error:

{ 'name': 'Alice' }  // INVALID - single quotes
{ "name": "Alice" }  // VALID

3. Unquoted Keys

JavaScript allows unquoted object keys, but JSON does not:

{ name: "Alice" }    // INVALID - unquoted key
{ "name": "Alice" }  // VALID

4. Comments

JSON has no comment syntax. Neither // nor /* */ are valid. If you need comments in config files, consider using JSONC (JSON with Comments, supported by VS Code) or YAML instead. Alternatively, use a "_comment" key:

{ "_comment": "Timeout in milliseconds", "timeout": 5000 }

5. Missing Commas

Forgetting a comma between items is easy to miss in large files. Your JSON parser will report an "unexpected token" error at the position where the comma should be.

JSON Validation Best Practices

Syntax checking (is it valid JSON?) is just the first step. Robust applications also validate structure, types, and constraints:

  • Syntax validation: Use JSON.parse() inside a try/catch block. If it throws, the JSON is malformed.
  • Schema validation: Define expected structure using JSON Schema. Validate incoming data at API boundaries using libraries like Ajv (JavaScript), jsonschema (Python), or Newtonsoft (C#).
  • Type checking: Ensure values match expected types. A "price" field should be a number, not a string like "19.99".
  • Required fields: Define which fields are mandatory and reject payloads missing them.
  • CI/CD integration: Lint JSON config files in your build pipeline. Catch formatting issues before they reach production.

Format Your JSON Now

Our JSON Formatter & Validator lets you paste any JSON, instantly see syntax errors with line numbers, and format with your preferred indentation — all running 100% in your browser. No data is ever sent to a server.

Frequently Asked Questions

Both are valid. 2 spaces is more common in JavaScript/TypeScript projects and is the default for tools like Prettier. 4 spaces is common in Java and Python projects. The most important thing is consistency within your project. Pick one and configure your formatter to enforce it.
Use minified JSON for API responses, network transmission, and storage where size matters. A 100KB pretty-printed JSON file might be only 60KB minified. Use pretty-printed JSON for configuration files, debugging, documentation, and anything humans need to read or edit. Version-controlled JSON should be pretty-printed for meaningful git diffs.
The five most common errors are: trailing commas after the last item in an array or object, single quotes instead of double quotes for strings, unquoted property keys, comments (JSON does not support comments), and missing commas between items. All of these will cause JSON.parse() to throw a SyntaxError.
It depends on your ecosystem. JavaScript/TypeScript APIs typically use camelCase (userName, createdAt). Python and Ruby APIs typically use snake_case (user_name, created_at). Google's JSON style guide recommends camelCase. The key is consistency across your entire API — document your convention and enforce it with linting.
Use JSON Schema to define the expected structure, types, and constraints of your data. Validate incoming JSON against the schema at API boundaries. In JavaScript, use JSON.parse() inside a try/catch block for syntax validation. For structure validation, libraries like Ajv (JavaScript) or jsonschema (Python) validate against JSON Schema definitions.