JSON (JavaScript Object Notation) has become the standard format for data exchange in web APIs. Understanding how to properly structure, validate, and format JSON is essential for building robust APIs and web applications.

What is JSON?

JSON is a lightweight, text-based data interchange format that's easy for humans to read and write, and easy for machines to parse and generate. Despite its name suggesting JavaScript origins, JSON is language-independent and supported by virtually every programming language.

Why JSON?

  • Simplicity: Easy to read and understand
  • Lightweight: Minimal overhead compared to XML
  • Native JavaScript support: Parsed directly in browsers
  • Universal: Supported by all major languages

JSON Syntax Basics

Data Types

JSON supports six data types:

{
    "string": "Hello, World!",
    "number": 42,
    "float": 3.14159,
    "boolean": true,
    "null": null,
    "array": [1, 2, 3],
    "object": {
        "nested": "value"
    }
}

Common Syntax Errors

  • Trailing commas: {"a": 1,} is invalid
  • Single quotes: Always use double quotes
  • Unquoted keys: {name: "value"} is invalid
  • Comments: JSON doesn't support comments

Pro Tip

Use our JSON Formatter to validate and beautify your JSON data instantly.

Structuring API Responses

Successful Response

A well-structured success response:

{
    "success": true,
    "data": {
        "user": {
            "id": 123,
            "name": "John Doe",
            "email": "john@example.com"
        }
    },
    "meta": {
        "timestamp": "2025-01-06T12:00:00Z",
        "version": "1.0"
    }
}

List/Collection Response

When returning multiple items with pagination:

{
    "success": true,
    "data": {
        "items": [
            {"id": 1, "name": "Item 1"},
            {"id": 2, "name": "Item 2"}
        ]
    },
    "pagination": {
        "page": 1,
        "per_page": 20,
        "total": 100,
        "total_pages": 5
    }
}

Error Response Patterns

Standard Error Response

{
    "success": false,
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "The request contains invalid data",
        "details": [
            {
                "field": "email",
                "message": "Invalid email format"
            }
        ]
    }
}

HTTP Status Code Mapping

  • 200 OK: Successful request
  • 201 Created: Resource successfully created
  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Authentication required
  • 403 Forbidden: Access denied
  • 404 Not Found: Resource doesn't exist
  • 422 Unprocessable Entity: Validation errors
  • 500 Internal Server Error: Server-side error

JSON Validation

Using JSON Schema

JSON Schema allows you to define the structure your JSON should follow:

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

Best Practices

Naming Conventions

  • Use camelCase or snake_case consistently
  • Be descriptive but concise
  • Use plural names for arrays: "users" not "user"
  • Avoid abbreviations that aren't widely understood

Performance

  • Minimize response payload size
  • Use pagination for large datasets
  • Consider compression (gzip) for responses
  • Avoid deeply nested structures

Security

  • Never include sensitive data in responses
  • Sanitize user input before serialization
  • Use proper Content-Type headers
  • Implement rate limiting

Worked example: debug an API response

The following is a deliberately broken example, not a response captured from a customer. Paste it into our JSON Formatter to investigate the syntax:

{
  "orderId": "00042",
  "total": 19.95,
  "paid": True,
}

There are two syntax errors: True must be lowercase true, and the comma after the final property must be removed. Once corrected, the document can be parsed:

{
  "orderId": "00042",
  "total": 19.95,
  "paid": true
}

Keep orderId as a string. Converting it to a number discards its leading zeros. For identifiers, preserve the representation agreed by the API contract. Formatting should improve readability without changing meaning.

Valid JSON can still be the wrong response

If your backend expects totalCents as an integer, the corrected example still violates that contract. The formatter validates JSON syntax; it does not apply the JSON Schema above or know your application's required fields. Test the parsed object against your backend schema as a separate step.

When the input starts with an HTML tag

An error mentioning < near the beginning may mean you pasted an HTML error or login page. Inspect the HTTP status and Content-Type before editing the body. Fix the authentication, route or upstream failure that returned HTML; removing angle brackets does not recover the intended JSON.

Use a redacted example when sharing a failure. Remove bearer tokens, session cookies and personal data while keeping the types and nesting needed to reproduce the problem. For the grammar itself, refer to RFC 8259.

Putting the response into use

Well-structured JSON is the foundation of a great API. By following these best practices for formatting, error handling, and validation, you'll create APIs that are easy to use, maintain, and debug.

Try our JSON Formatter to validate and beautify your JSON data, or convert from other formats using our CSV to JSON Converter.