JSON Formatting Tips Every Developer Should Know
Master JSON formatting, validation, and debugging. Common mistakes and how to avoid them when working with JSON data.
JSON (JavaScript Object Notation) is the lingua franca of modern APIs. It's simple and readable, but even experienced developers run into frustrating formatting errors. Here's what you need to know.
The Most Common JSON Mistakes
- Trailing commas — JSON doesn't allow a comma after the last item in an array or object
- Single quotes — JSON requires double quotes for both keys and string values
- Unquoted keys — Unlike JavaScript objects, JSON keys must always be in quotes
- Comments — JSON does not support comments (// or /* */)
- Undefined values — JSON doesn't have undefined, only null
Valid vs Invalid JSON
// INVALID — single quotes, trailing comma, comment
{
'name': 'Alice',
"age": 30, // user age
}
// VALID
{
"name": "Alice",
"age": 30
}Pretty Printing vs Minifying
Pretty-printed JSON uses indentation and newlines for human readability. Minified JSON removes all whitespace to reduce file size. Use pretty-printed JSON during development and debugging; use minified JSON for API responses and data transfer in production.
Tip
Use a JSON formatter with syntax highlighting to spot errors instantly. Most formatters will show you the exact line and character where a parse error occurs.
Working with Nested JSON
Deeply nested JSON can be hard to read. A good JSON formatter with collapsible tree view lets you expand and collapse nodes. When debugging, focus on one level at a time.
JSON Schema Validation
JSON Schema is a standard for defining the structure of JSON data. It lets you specify which fields are required, what types they should be, and validation rules like minimum/maximum values. This is invaluable for API documentation and automated testing.
Useful JSON Tips for Everyday Work
- Use JSON.stringify(obj, null, 2) in JavaScript/Node.js to pretty-print
- Use jq in the terminal to query and transform JSON from command line
- Store config files as JSON but comment by using "_comment" keys as a workaround
- When comparing two JSON files, normalize them first (sort keys) for a clean diff