Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool

JSON Formatting Best Practices

A Guide to Writing Readable, Maintainable, and Interoperable JSON

Introduction: Why Formatting Matters

JSON (JavaScript Object Notation) is the de facto standard for data interchange on the web. Its simplicity and human-readability are key to its popularity. However, poorly formatted JSON can quickly become difficult to read, debug, and maintain, especially as data structures grow more complex. Adhering to consistent formatting best practices ensures that your JSON is easy to work with for both humans and machines.

While JSON parsers are generally flexible with whitespace, consistent formatting provides significant benefits in:

  • Readability: Easier for developers to understand the structure and data.
  • Maintainability: Simplifies debugging and modifying JSON data.
  • Version Control: Makes it easier to see differences (diffs) in JSON files when tracked in systems like Git.
  • Interoperability: Though parsers are lenient, some tools or manual inspections might rely on predictable formatting.

Core Principles: Indentation and Spacing

The most fundamental aspect of JSON formatting is indentation and spacing. While not required by the JSON specification itself, consistent use of whitespace vastly improves readability.

Indentation

Use consistent indentation to represent nested structures. The most common indentation levels are 2 or 4 spaces. Avoid using tabs as their visual representation varies across different editors and environments.

Good (2 Spaces):

{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "address": {
    "street": "123 Main St",
    "city": "Anytown"
  },
  "courses": [
    "Math",
    "Science",
    "History"
  ]
}

Bad (No Indentation):

{"name":"Alice","age":30,"isStudent":false,"address":{"street":"123 Main St","city":"Anytown"},"courses":["Math","Science","History"]}

Spacing

Use spacing around colons (`:`) and commas (`,`) to separate keys, values, and elements clearly.

  • Place a space after the colon separating a key and its value (`"key": value`).
  • Place a space after the comma separating key-value pairs in an object or elements in an array (`value1, value2`).

Good Spacing:

{
  "key1": "value1",
  "key2": {
    "nestedKey": 123
  },
  "array": [ "item1", "item2" ]
}

Bad Spacing:

{
  "key1":"value1",
  "key2":{"nestedKey":123},
  "array":["item1","item2"]
}

Key Naming Conventions

While JSON keys are always strings, consistent naming helps developers predict and understand the data structure. Common conventions include:

  • camelCase: Starts with a lowercase letter, subsequent words start with uppercase (e.g., `firstName`, `totalAmountDue`). This is common in JavaScript/frontend contexts.
  • snake_case: All lowercase letters, words separated by underscores (e.g., `first_name`, `total_amount_due`). Common in Python and database contexts.
  • PascalCase: Starts with an uppercase letter, subsequent words start with uppercase (e.g., `FirstName`, `TotalAmountDue`). Sometimes used for types or classes, less common for general JSON keys.

Choose one convention and stick to it across your entire project or API. Avoid using hyphens (`-`) in keys as they can cause issues when trying to access properties directly in JavaScript using dot notation (e.g., `object.first-name` is invalid).

Example (camelCase):

{
  "userId": "12345",
  "productDetails": {
    "productName": "Laptop",
    "priceUsd": 1200.50
  }
}

Example (snake_case):

{
  "user_id": "12345",
  "product_details": {
    "product_name": "Laptop",
    "price_usd": 1200.50
  }
}

Data Types and Their Usage

JSON supports six basic data types: strings, numbers, booleans, arrays, objects, and null. Using the correct type is crucial for data integrity and ease of parsing.

  • Strings: Must be enclosed in double quotes. Includes characters, dates (often represented as strings), and any text data.
  • Numbers: Integers or floating-point numbers. Do not use quotes around them.
  • Booleans: true or false (lowercase). Do not use quotes.
  • Arrays: Ordered collections of values, enclosed in square brackets [ ]. Values can be of any JSON type.
  • Objects: Unordered collections of key-value pairs, enclosed in curly braces { }. Keys must be strings; values can be of any JSON type.
  • Null: Represents an empty or non-existent value. Always null (lowercase). Do not use quotes.

Common Pitfalls:

  • Putting quotes around numbers or booleans (e.g., `"123"`, `"true"`). This makes them strings, which might require extra parsing on the receiving end.
  • Incorrect:

    { "count": "123", "isActive": "false" }

    Correct:

    { "count": 123, "isActive": false }
  • Using single quotes for strings or keys. JSON requires double quotes.
  • Incorrect:

    { 'name': 'Bob' }

    Correct:

    { "name": "Bob" }

Handling Nulls and Empty Values

How you represent missing or empty data can impact how easy the JSON is to consume.

  • Use null for intentionally missing values: If a key exists but has no value, null is the appropriate representation.
  • Omit keys for truly optional fields: If a field is entirely optional and no value exists, consider omitting the key altogether rather than including it with a null value, unless the schema specifically requires the key to be present.
  • Use empty strings, arrays, or objects for empty collections: If a value represents a list or structure that is currently empty, use [] or {} instead of null.

Example:

{
  "name": "Charlie",
  "email": null,        // email exists but is not provided
  "phone": "123-456-7890",
  // "address" key is omitted if address is optional and not present

  "tags": [],           // list of tags is empty
  "preferences": {}     // preferences object is empty
}

Consistency is key here. Define and document your strategy for nulls and empty values.

Date and Time Formats

JSON does not have a built-in date or time type. Dates and times are typically represented as strings. The most widely accepted and recommended format is ISO 8601.

  • ISO 8601: This format is unambiguous and includes timezone information (e.g., "2023-10-27T10:00:00Z" for UTC or "2023-10-27T10:00:00+01:00" for a specific timezone).
  • Avoid custom string formats (e.g., "MM/DD/YYYY") or timestamps (seconds/milliseconds since epoch) unless there's a strong reason and it's clearly documented, as they can lead to ambiguity or overflow issues.

Example (ISO 8601):

{
  "event_name": "Conference",
  "start_time": "2024-01-15T09:00:00Z",
  "end_time": "2024-01-17T17:00:00-05:00"
}

Order of Keys

The JSON specification states that object keys are unordered. While most parsers maintain insertion order or sort keys alphabetically for convenience, you should never rely on the order of keys in a JSON object.

For human readability and predictable diffs in version control, however, consistently sorting keys (often alphabetically) can be helpful. Tools like linters and formatters can automate this.

Comments

Standard JSON does not support comments. Including comments will result in a parsing error.

If you need to add descriptive information about your JSON structure, consider these alternatives:

  • External Documentation: Use accompanying documentation (like OpenAPI/Swagger specs) to describe the JSON structure, field meanings, types, and constraints.
  • JSON Schema: Define a formal schema for your JSON (see next section).
  • Wrapper Objects: If you need to add metadata to the JSON itself, wrap the data inside an object that includes separate keys for data and metadata.

Alternative (Wrapper Object):

{
  "metadata": {
    "description": "List of users",
    "count": 3
  },
  "data": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" },
    { "id": 3, "name": "Charlie" }
  ]
}

Schema Validation

For APIs and complex data structures, defining and validating your JSON against a schema is a critical best practice. JSON Schema is a popular specification for this purpose.

  • Clearly defines the structure, data types, required fields, and constraints.
  • Allows for automated validation on both the sending and receiving ends.
  • Serves as excellent documentation for the data format.

Simple JSON Schema Example:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer", "minimum": 0 },
    "isStudent": { "type": "boolean" }
  },
  "required": [ "name", "age" ],
  "additionalProperties": false
}

Tools are available in most programming languages to validate JSON against a JSON Schema.

Security Considerations: JSON Hijacking

A historical vulnerability involved returning a JSON array or object literal directly as a top-level response to a GET request. Malicious pages on other origins could potentially hijack this data.

If the sensitive data was returned as a simple JSON array (e.g., [{...}, {...}]), this response was also a valid JavaScript array literal. In some scenarios (especially pre-ES5 browsers or specific execution contexts like overriding Array constructors), the malicious page could potentially read the values of this array. Similarly, if it was a simple object literal ({...}), it could potentially be assigned to a variable if the response was wrapped in parentheses.

Best Practice Mitigation:

  • Always return JSON data inside a top-level object ({ "data": [...] }). This is not a valid JavaScript literal for direct execution.
  • Set the correct Content-Type header (application/json).
  • Use CSRF tokens and strictly enforce request methods (e.g., require POST for sensitive operations).

Safe Response Structure:

{
  "status": "success",
  "data": [
    { "item": "A", "value": 10 },
    { "item": "B", "value": 20 }
  ]
}

Returning a top-level array like [{ ... }, { ... }] is generally discouraged for GET requests returning sensitive data.

Automated Formatting and Linting

Manually enforcing all these rules can be tedious. Leverage tools to automate the process:

  • Formatters: Tools like Prettier or integrated IDE formatters (VS Code, WebStorm, etc.) can automatically format JSON files on save or commit according to configurable rules (indentation, spacing, key sorting).
  • Linters: Linters can check for potential issues beyond just formatting, although for pure JSON, formatters are often sufficient.
  • Online Validators/Formatters: Websites are available to paste and validate/format JSON snippets for quick checks.

Conclusion

Consistent JSON formatting is a simple yet powerful practice that significantly improves the developer experience and reduces errors. By applying clear rules for indentation, spacing, key naming, data types, and handling nulls/empty values, you create JSON that is easy to read, write, and parse. Combined with schema validation and awareness of security considerations, you build more robust and maintainable systems that rely on JSON data exchange. Adopt automated tools to enforce these practices and make them a standard part of your development workflow.

Need help with your JSON?

Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool