Skip to main content
ToolFocus
Developer7 min readBy

How to Format JSON: Best Practices for Clean, Readable Data

A complete guide to JSON formatting best practices — indentation, naming conventions, schema validation, and tools to keep your JSON clean across a team.

Estimated reading time: 7 minutes

Formatting JSON consistently and correctly is a fundamental skill for web developers. Clean JSON improves readability, reduces bugs, and makes collaboration far easier. This guide covers everything from indentation choices to naming conventions, schema validation, and tooling that keeps your JSON spotless across a team.

> Quick start: Use our free [JSON Formatter](/tools/json-formatter) to instantly clean up any messy or minified JSON — paste and format in one click.

The Basics: Indentation and Structure

The most visible aspect of JSON formatting is indentation. The two dominant conventions are 2-space and 4-space indentation. Neither is objectively correct — what matters is consistency within a project.

2-space indentation is the default for most Node.js and JavaScript projects. It produces compact files that are easy to read without excessive horizontal scroll on nested objects.

4-space indentation is preferred in Python-heavy projects and some enterprise environments where deeper nesting must remain readable.

Tab indentation exists but is less common in JSON since JSON is often generated programmatically and tabs can behave inconsistently across editors.

For project configuration files like package.json or .prettierrc, the built-in tools typically enforce their own format — follow those rather than imposing your own.

Naming Conventions for JSON Keys

Advertisement

JSON keys are strings, which means technically anything goes. In practice, there are four common naming styles:

camelCase (firstName, createdAt) — The JavaScript standard. Best for JSON consumed directly by JavaScript frontends.

snake_case (first_name, created_at) — Common in Python and Ruby APIs. Readable but inconsistent with JS variable names.

PascalCase (FirstName, CreatedAt) — Rare in JSON, more common in C# / .NET environments.

kebab-case (first-name, created-at) — Avoided in JSON because hyphens cannot be used in JavaScript identifier names without bracket notation.

The key rule: pick one convention and apply it uniformly across your entire API. Mixed conventions create bugs and confusion.

Ordering Keys for Readability

JSON does not specify key ordering — parsers may return keys in any order. However, for human-readable files, a consistent ordering convention greatly improves comprehension:

1. Identifier fields first (id, type, name)

2. Required fields before optional fields

3. Timestamps last (createdAt, updatedAt, deletedAt)

4. Nested objects at the end

Many JSON formatters include an option to sort keys alphabetically. This is useful for diffs — alphabetically sorted keys make it obvious when a field was added or removed.

Handling Null and Optional Fields

A frequent question is whether to include fields with null values or omit them entirely. Both approaches are valid, but each has trade-offs.

Include null fields: Your API response has a consistent shape on every call. Consumers know what fields to expect and can write simple, predictable code.

Omit null fields: Smaller payload size. Useful when most fields are optional and only a few are typically populated.

A hybrid approach works well: always include required identifier and status fields even if null, but omit optional descriptive fields when not set.

Validating JSON with a Schema

JSON Schema is a powerful tool for validating that JSON data conforms to an expected structure. A simple schema looks like this:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "type": "object",
  "required": ["id", "name", "email"],
  "properties": {
    "id": { "type": "integer" },
    "name": { "type": "string", "minLength": 1 },
    "email": { "type": "string", "format": "email" },
    "age": { "type": "integer", "minimum": 0, "maximum": 120 }
  }
}

Libraries like ajv (JavaScript) and jsonschema (Python) can validate data against a schema at runtime, catching invalid data before it reaches your database.

JSON in Code Reviews

One of the highest-value applications of consistent JSON formatting is in code reviews. When configuration files, fixtures, or mock API responses are committed to version control, well-formatted JSON makes diffs meaningful. A change to a single value shows up as one changed line, not a complete file rewrite.

Use tools like Prettier or ESLint with eslint-plugin-json to automatically format JSON files on save or as a pre-commit hook. This eliminates formatting debates in pull requests entirely.

Minification for Production

While formatted JSON is ideal for development, minified JSON is better for production API responses. Removing all whitespace from a 50KB JSON response can reduce it to 30KB — a 40% saving that adds up significantly at scale.

Most backend frameworks offer a "pretty print" mode for development and minified output for production. In Express.js, setting app.set('json spaces', 2) in development and leaving it unset in production handles this automatically.

Practical Tips for Daily JSON Work

  • Keep a [JSON Formatter](/tools/json-formatter) bookmarked for quick debugging.
  • When pasting JSON into documentation or chat messages, always format it first.
  • Use JSON.stringify(data, null, 2) in console.log calls during debugging to get readable output.
  • In VS Code, the built-in "Format Document" command formats JSON files automatically.
  • If your JSON includes encoded strings, our [Base64 decoder](/tools/base64) can help inspect embedded data.

Working with Deeply Nested JSON

Deep nesting is a JSON anti-pattern. If you find yourself with 5 or more levels of nesting, consider whether the data model should be flattened or split into separate API endpoints. A good rule of thumb is to keep nesting to 3 levels maximum for readability.

Need to work with tabular data instead? Our [CSV to JSON converter](/tools/csv-to-json) can flatten structured data into clean JSON arrays.

JSON Comments: A Workaround

Standard JSON does not support comments, which is a pain point for configuration files. Common workarounds include:

  • Using a dedicated key like "_comment" for documentation purposes
  • Switching to JSONC (JSON with Comments) supported by VS Code and TypeScript configs
  • Migrating to YAML for config files where comments add significant value

Frequently Asked Questions

Q: Should I use 2 or 4 spaces to format JSON?

Either works — what matters most is consistency. Most JavaScript and Node.js projects default to 2 spaces; Python projects often use 4. Check if your project already has a Prettier or ESLint config that enforces a choice.

Q: How do I format JSON in VS Code?

Open the JSON file, press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac), or right-click and select "Format Document." VS Code uses your editor settings for indentation.

Q: How do I format JSON in a terminal?

Use the jq command: cat file.json | jq . — this pretty-prints any JSON file. You can also use python3 -m json.tool file.json without any extra installation.

Q: Why is my JSON throwing a "trailing comma" error?

JSON (unlike JavaScript) does not allow trailing commas after the last item in an array or object. Remove the extra comma and re-validate using our [JSON Formatter](/tools/json-formatter).

Conclusion

Good JSON formatting is a simple discipline with outsized rewards. It makes debugging faster, collaboration smoother, and code reviews more productive. By adopting consistent conventions for indentation, key naming, null handling, and schema validation, you write cleaner APIs and more maintainable applications. [Use ToolHub's JSON Formatter](/tools/json-formatter) anytime you need to quickly format or validate JSON — no setup, no friction, just clean results.

Tags:#json#best practices#formatting#developer

ToolFocus

ToolFocus editorial team

Found this helpful?

Share it with your team or bookmark it for later.

Advertisement

More from the ToolFocus Blog