Tool Guides

JSON Formatter: Pretty Print and Validate JSON

Learn how to format, validate, and pretty print JSON data for easier reading, debugging, and development.

7 min read

JSON (JavaScript Object Notation) is the standard data format for web APIs and configuration files. While minified JSON is efficient for transmission, it is nearly impossible to read. Understanding JSON structure and common errors helps you debug APIs and work with data more effectively. The JSON Formatter pretty prints and validates your JSON instantly.

What is JSON Pretty Print?

Pretty printing transforms compact, minified JSON into formatted, indented text that humans can easily read. The process adds line breaks and consistent indentation to reveal the data structure without changing the data itself.

Minified JSON (78 bytes):

{"name":"John","age":30,"city":"New York","skills":["JavaScript","Python"]}

Pretty printed JSON (155 bytes, same data):

{
    "name": "John",
    "age": 30,
    "city": "New York",
    "skills": [
        "JavaScript",
        "Python"
    ]
}

Both representations contain identical data. Minified JSON saves bandwidth in transmission; pretty printed JSON is for human reading and editing.

Why Format JSON?

JSON formatting provides several important benefits:

  • Readability: Understand data structure at a glance instead of parsing mentally
  • Debugging: Find issues in API responses quickly by seeing the hierarchy
  • Documentation: Present clean examples in docs and tutorials
  • Comparison: Formatted JSON diffs more clearly than single-line JSON
  • Error detection: Validators catch syntax errors before they cause runtime failures
  • Learning: Understand nested data structures when working with unfamiliar APIs

Common Use Cases

API Development and Debugging

Format API responses during development for easier debugging. A backend developer troubleshooting an e-commerce checkout flow formatted the API response to discover that the shipping address was nested three levels deep, not two as documented. Seeing the structure revealed the bug in seconds instead of hours of trial and error.

Configuration Files

Keep config files readable with consistent formatting so team members can understand and modify settings more easily. A DevOps engineer managing Kubernetes configs uses formatted JSON with sorted keys so changes are obvious in git diffs.

Data Exchange and Integration

Validate JSON before sending to other systems. A data engineer integrating two systems discovered that their JSON export had trailing commas (invalid) that the source system tolerated but the target system rejected. Validation caught the error before a failed production import.

Log Analysis and Monitoring

Format JSON log entries for investigation. Modern logging systems like ELK store logs as JSON. Pretty printing structured log entries makes it possible to scan for specific fields visually during incident response.

API Documentation

API documentation requires example requests and responses. Formatted JSON helps developers understand expected data structures. Poorly formatted examples in documentation are a common source of integration errors.

JSON Validation

Validators catch common JSON errors that cause parsing failures:

Missing Quotes Around Keys

Unlike JavaScript objects, JSON requires all keys to be double-quoted:

// Invalid (unquoted key):
{name: "John"}

// Valid:
{"name": "John"}

Trailing Commas

JSON does not allow trailing commas after the last element:

// Invalid (trailing comma):
{"name": "John", "age": 30,}
["a", "b", "c",]

// Valid:
{"name": "John", "age": 30}
["a", "b", "c"]

Single Quotes

JSON requires double quotes for strings. Single quotes are invalid:

// Invalid:
{'name': 'John'}

// Valid:
{"name": "John"}

Comments

JSON does not support comments. Use JSON5 or YAML if you need comments, or document separately:

// Invalid (comments not allowed in JSON):
{
    "name": "John"  // User's name
}

// Valid (no comments):
{
    "name": "John"
}

Unescaped Control Characters

Control characters like newlines must be escaped in strings:

// Invalid (literal newline in string):
{"text": "line 1
line 2"}

// Valid (escaped newline):
{"text": "line 1\nline 2"}

Understanding JSON Structure

Objects (Dictionaries/Maps)

Curly braces contain unordered key-value pairs:

{
    "string": "text value",
    "number": 42,
    "float": 3.14,
    "boolean": true,
    "null": null
}

Arrays (Lists)

Square brackets contain ordered lists of values:

{
    "numbers": [1, 2, 3, 4, 5],
    "mixed": ["string", 42, true, null]
}

Nested Structures

Objects and arrays can contain other objects and arrays to any depth:

{
    "user": {
        "name": "John",
        "addresses": [
            {"city": "New York", "type": "home"},
            {"city": "Boston", "type": "work"}
        ]
    }
}

Data Types

JSON supports six data types:

  • String: "text" (must use double quotes)
  • Number: 42, 3.14, -5, 1.2e10 (no quotes, no leading zeros)
  • Boolean: true, false (lowercase, no quotes)
  • Null: null (lowercase, no quotes)
  • Object: {"key": "value"}
  • Array: [1, 2, 3]

JSON Formatting in Code

Here are examples of formatting JSON in popular languages:

JavaScript

// Pretty print with 2-space indent (most common)
const formatted = JSON.stringify(obj, null, 2);

// Pretty print with 4-space indent
const formatted = JSON.stringify(obj, null, 4);

// Pretty print with tab indent
const formatted = JSON.stringify(obj, null, '\t');

// Parse and format a JSON string
const formatted = JSON.stringify(JSON.parse(jsonString), null, 2);

// With replacer function (filter/transform)
const filtered = JSON.stringify(obj, ['name', 'age'], 2);

Python

import json

# Pretty print with 2-space indent
formatted = json.dumps(obj, indent=2)

# With sorted keys (for consistent diffs)
formatted = json.dumps(obj, indent=2, sort_keys=True)

# Ensure ASCII-safe output
formatted = json.dumps(obj, indent=2, ensure_ascii=True)

# Format a JSON file
with open('data.json') as f:
    data = json.load(f)
print(json.dumps(data, indent=2))

Command Line Tools

# Using jq (most powerful, needs installation)
cat data.json | jq '.'          # Pretty print
cat data.json | jq '.users'      # Extract field
cat data.json | jq -c '.'        # Minify

# Using Python (pre-installed on most systems)
cat data.json | python -m json.tool

# Using Node.js
node -e "console.log(JSON.stringify(require('./data.json'), null, 2))"

Advanced Techniques

Sorting Keys for Consistent Diffs

When JSON files are version controlled, sorted keys make diffs meaningful:

# Python: Sort keys alphabetically
json.dumps(obj, indent=2, sort_keys=True)

# JavaScript: Sort keys with replacer
const sortedJson = JSON.stringify(obj, Object.keys(obj).sort(), 2);

Validating JSON Schema

Beyond syntax validation, JSON Schema validates data structure:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "required": ["name", "email"],
    "properties": {
        "name": {"type": "string"},
        "email": {"type": "string", "format": "email"}
    }
}

Working with Large JSON Files

For large JSON files that do not fit in memory, use streaming parsers like Python's ijson or JavaScript's clarinet. These parse JSON incrementally without loading the entire file.

Common Mistakes to Avoid

These errors frequently cause JSON problems:

  • Using single quotes: JSON requires double quotes. This is the most common error when converting JavaScript to JSON.
  • Including trailing commas: JavaScript allows trailing commas; JSON does not. Editors with JSON linting catch this.
  • Forgetting to escape backslashes: File paths need double backslashes: "C:\\Users\\file.txt"
  • Including comments: JSON has no comment syntax. Use JSON5 or YAML if you need comments.
  • Using undefined: JavaScript's undefined is not valid JSON. Use null instead.
  • Including functions: Functions cannot be serialized to JSON. They are silently removed.

JSON vs Other Formats

Compare JSON with alternative data formats:

  • XML: More verbose but supports attributes, namespaces, and mixed content. Better for document markup.
  • YAML: More human-readable, supports comments, but whitespace-sensitive. Popular for configuration.
  • CSV: Much simpler but only for flat tabular data. Cannot represent nested structures.
  • TOML: Designed for configuration files. More readable than JSON, supports comments.
  • Protocol Buffers: Binary format, much smaller and faster than JSON. Requires schema definition.

Best Practices

Follow these guidelines when working with JSON:

  • Validate before use: Always check JSON syntax before processing to catch errors early
  • Use consistent indentation: 2 or 4 spaces is standard; pick one for your project
  • Minify for production: Remove whitespace to reduce file size for transmission
  • Sort keys for version control: Sorted keys produce meaningful diffs
  • Use descriptive key names: "firstName" is better than "fn" or "n1"
  • Keep backups: Save original JSON before making programmatic changes

Related Tools

Complete your data processing workflow with these tools:

Conclusion

JSON formatting is essential for developers working with APIs, configurations, and data exchange. Understanding common validation errors like trailing commas and single quotes helps you debug faster. Pretty printed JSON with consistent indentation makes code review, documentation, and collaboration significantly easier. The JSON Formatter validates and formats your JSON instantly, catching syntax errors and producing readable output that reveals your data structure clearly.

Found this helpful?

Share it with your friends and colleagues

Written by

Admin

Contributing writer at TextTools.cc, sharing tips and guides for text manipulation and productivity.

Cookie Preferences

We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies.

Cookie Preferences

Manage your cookie settings

Essential Cookies
Always Active

These cookies are necessary for the website to function and cannot be switched off. They are usually set in response to actions made by you such as setting your privacy preferences or logging in.

Functional Cookies

These cookies enable enhanced functionality and personalization, such as remembering your preferences, theme settings, and form data.

Analytics Cookies

These cookies allow us to count visits and traffic sources so we can measure and improve site performance. All data is aggregated and anonymous.

Google Analytics _ga, _gid

Learn more about our Cookie Policy