How to Format JSON: A Complete Guide for Developers
JSON is the backbone of modern APIs and configuration files. Yet poorly formatted JSON is one of the most common sources of debugging headaches. This guide covers everything you need to know about formatting, validating, and working with JSON data effectively.
What Is JSON and Why Does Formatting Matter?
JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for web APIs, configuration files, and data storage. Originally derived from JavaScript, JSON is now used across virtually every programming language including Python, Java, Go, Ruby, and C#.
Properly formatted JSON is crucial for several reasons. First, it makes data readable for humans who need to inspect API responses or configuration files. Second, well-formatted JSON helps you spot errors quickly — a missing comma or misplaced bracket becomes obvious when the data is properly indented. Third, many tools and editors rely on correct JSON formatting to provide syntax highlighting and auto-completion.
Consider the difference between minified and formatted JSON. A minified API response might look like this:
{"users":[{"id":1,"name":"Alice","roles":["admin","editor"]},{"id":2,"name":"Bob","roles":["viewer"]}],"total":2}The same data, properly formatted with 2-space indentation, becomes immediately readable:
{
"users": [
{
"id": 1,
"name": "Alice",
"roles": ["admin", "editor"]
},
{
"id": 2,
"name": "Bob",
"roles": ["viewer"]
}
],
"total": 2
}Common JSON Syntax Errors and How to Fix Them
Even experienced developers run into JSON syntax errors regularly. Here are the most common mistakes and how to resolve them.
Trailing Commas
Unlike JavaScript objects, JSON does not allow trailing commas. A trailing comma after the last property in an object or the last element in an array will cause a parse error. This is arguably the most frequent JSON mistake developers make, especially when copying data from JavaScript code.
// Invalid - trailing comma
{ "name": "Alice", "age": 30, }
// Valid
{ "name": "Alice", "age": 30 }Single Quotes Instead of Double Quotes
JSON strictly requires double quotes for both keys and string values. Single quotes, while valid in JavaScript and Python dictionaries, will cause a JSON parse error. If you are converting Python dictionaries to JSON, watch out for this common pitfall.
Unquoted Keys
All keys in JSON must be strings wrapped in double quotes. While JavaScript allows unquoted property names, JSON does not. Always ensure every key is a properly quoted string.
Comments in JSON
Standard JSON does not support comments. If you need comments in configuration files, consider using JSONC (JSON with Comments, supported by VS Code), JSON5, or YAML as alternatives. Some tools like TypeScript's tsconfig.json use JSONC, which is why comments work there but not in standard JSON parsers.
JSON Formatting Methods: From Command Line to Online Tools
Using the Command Line
Python's built-in json.tool module can format JSON directly from the command line:
echo '{"name":"Alice","age":30}' | python3 -m json.toolIf you have jq installed, it is even more powerful and is the go-to tool for JSON processing in shell scripts:
curl -s https://api.example.com/users | jq '.'
cat config.json | jq '.database.host'In Your Code Editor
Most modern editors have built-in JSON formatting. In VS Code, open a JSON file and press Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac) to auto-format the document. You can also configure the default formatter and indentation size in your settings.
Programmatic Formatting
Every major programming language provides built-in JSON formatting capabilities:
// JavaScript / Node.js
JSON.stringify(data, null, 2)
# Python
import json
json.dumps(data, indent=2, ensure_ascii=False)
// Go
json.MarshalIndent(data, "", " ")Online JSON Formatters
When you need to quickly format a JSON snippet from an API response or log file, an online formatter is the fastest option. The key advantages are: no installation required, instant validation with error messages, and the ability to switch between different indentation styles. For sensitive data, choose a tool that processes everything client-side so your data never leaves your browser.
Advanced JSON Techniques
JSON Path Queries
JSON Path is a query language for extracting specific values from complex JSON structures. It works similarly to XPath for XML. For example, $.users[*].name extracts all user names from an array, and $.users[?(@.age > 25)] filters users by age. This is invaluable when working with large API responses.
Converting JSON to Other Formats
Developers frequently need to convert between JSON and other formats. Common conversions include JSON to CSV for spreadsheet analysis, JSON to TypeScript interfaces for type-safe frontend code, and JSON to YAML for Kubernetes and Docker configurations. Understanding these transformations saves significant time in daily development workflows.
JSON Schema Validation
For production applications, consider using JSON Schema to validate the structure and types of your JSON data. JSON Schema lets you define required fields, data types, string patterns, number ranges, and more. Tools like Ajv (JavaScript) and jsonschema (Python) can validate data against your schema at runtime, catching malformed data before it causes problems downstream.
Best Practices for Working with JSON
- Use consistent indentation. Pick 2 spaces or 4 spaces and stick with it across your project. Configure your editor and linter to enforce this automatically.
- Validate early. Parse and validate JSON at the boundary of your application — when receiving API requests or reading configuration files — not deep inside business logic.
- Use descriptive key names. Prefer
createdAtovercaanduserNameoverun. Clarity matters more than saving a few bytes. - Handle encoding correctly. JSON must be encoded in UTF-8. Make sure your application reads and writes JSON files with the correct encoding to avoid garbled characters.
- Be careful with numbers. JSON does not distinguish between integers and floats. Very large numbers (beyond 2^53) may lose precision in JavaScript. Use strings for IDs and other values where precision matters.
Related Tools
Try these free online tools to work with JSON more efficiently: