JSON Formatting Explained: A Guide for Developers
If you are a software developer today, whether you're building a massive microservices architecture or tinkering with a small weekend project, you deal with data. And when you deal with data on the web, you almost certainly deal with JSON.
JSON, or JavaScript Object Notation, has become the de facto standard for data interchange on the web. It's the language that APIs speak, the format that configuration files prefer, and the structure that NoSQL databases often use to store documents. Despite its ubiquity, many developers—both novice and experienced—occasionally stumble over its strict formatting rules. A misplaced comma or a forgotten quote can break an entire build or cause an application to crash in production.
In this comprehensive guide, we will dive deep into JSON formatting. We will cover the core syntax, essential rules, best practices for readability and maintainability, and common pitfalls to avoid. By the end of this article, you will have a solid understanding of how to craft perfect JSON every time.
What is JSON?
At its core, JSON is a lightweight, text-based, language-independent data interchange format. While its name includes "JavaScript," and its syntax is heavily inspired by JavaScript object literals, JSON is entirely language-agnostic. Almost every modern programming language—from Python and Ruby to Java and Go—has built-in or widely available libraries for parsing and generating JSON.
Why JSON Beat XML
If you were developing applications two decades ago, XML (eXtensible Markup Language) was the king of data exchange. XML is powerful and highly extensible, but it is also notoriously verbose. It requires opening and closing tags for every piece of data, which bloats the payload size and makes it harder for humans to read.
JSON emerged as a simpler, more lightweight alternative. It maps directly to the data structures used by most modern programming languages (objects/dictionaries/hash maps and arrays/lists). This direct mapping means less boilerplate, smaller payload sizes over the network, and a format that is genuinely human-readable.
The Core Syntax of JSON
The beauty of JSON lies in its simplicity. It is built on two primary structures, which are universally recognized across programming languages:
- A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Let's break down the data types that JSON supports.
Valid Data Types
JSON is strict about what constitutes a valid value. A value in JSON must be one of the following data types:
- String: A sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. For example:
"Hello, World!" - Number: A signed decimal number that may contain a fractional part and may use exponential E notation. It cannot include
NaNorInfinity. For example:42,-3.14,1.2e-5. - Object: An unordered collection of key-value pairs, enclosed in curly braces
{}. Keys must be strings. - Array: An ordered sequence of values, enclosed in square brackets
[]. - Boolean: Either
trueorfalse(all lowercase). - Null: An empty value, represented by the literal
null(all lowercase).
Objects and Arrays
Objects and arrays form the structural foundation of any JSON document.
Objects are defined using curly braces. Inside an object, data is represented as key-value pairs. Each key is separated from its value by a colon (:), and each pair is separated by a comma (,).
{
"firstName": "Jane",
"lastName": "Doe",
"age": 30,
"isDeveloper": true
}
Arrays are defined using square brackets. Inside an array, values are separated by commas. Arrays can contain values of different types, including other arrays and objects.
[
"Apple",
"Banana",
{
"type": "Fruit",
"name": "Cherry"
}
]
Essential JSON Formatting Rules
While JSON is simple, its parser is extremely strict. A single syntax error will render the entire document invalid. Here are the absolute golden rules you must follow.
1. Double Quotes are Mandatory
In JavaScript, you can use single quotes ('), double quotes ("), or backticks (`) to define strings. In JSON, you must use double quotes for strings. Furthermore, all object keys must be enclosed in double quotes.
Invalid JSON:
{
'name': 'John',
age: 25
}
Valid JSON:
{
"name": "John",
"age": 25
}
2. No Trailing Commas
This is perhaps the most common reason for JSON parsing errors. In modern JavaScript (and many other languages), it is perfectly fine—and often encouraged—to leave a comma after the last element in an object or array. This makes version control diffs cleaner. However, JSON strictly forbids trailing commas.
Invalid JSON:
{
"fruit": "Apple",
"color": "Red",
}
Valid JSON:
{
"fruit": "Apple",
"color": "Red"
}
3. Escaping Characters
If you need to include a double quote inside a JSON string, you must escape it using a backslash (\). You must also escape backslashes, control characters (like newlines \n and tabs \t), and you can use Unicode escapes (\uXXXX).
{
"quote": "He said, \"Hello!\"",
"path": "C:\\Windows\\System32"
}
Best Practices for JSON Formatting
Writing valid JSON is just the beginning. Writing good JSON ensures that your data is readable, maintainable, and predictable for the developers (and systems) consuming it.
Consistent Indentation
Because JSON ignores whitespace outside of strings, you could technically write an entire JSON document on a single line. However, minified JSON is nearly impossible for humans to read. Always format your JSON with consistent indentation.
The industry standard is typically 2 spaces or 4 spaces per indentation level. Most modern IDEs and formatters will do this automatically.
Meaningful Key Names
Choose a naming convention for your keys and stick to it. The most common conventions are camelCase (e.g., firstName) and snake_case (e.g., first_name).
APIs often prefer snake_case because it is highly readable and maps cleanly to database columns in many backend frameworks. However, JavaScript developers often prefer camelCase. Whichever you choose, consistency across your entire API is key. Avoid spaces or special characters in key names, even though they are technically allowed (if wrapped in double quotes).
Managing Nesting Depth
JSON allows you to nest objects and arrays infinitely. However, deeply nested data structures become difficult to parse, manipulate, and comprehend. As a rule of thumb, if your JSON object is nested more than four or five levels deep, it might be time to reconsider your data model. Flat data structures are generally easier to work with and perform better.
Common Pitfalls and How to Avoid Them
Even seasoned developers can trip over JSON's strictness. Here are some of the most frequent mistakes.
1. Attempting to Use Comments
Unlike many configuration formats (such as YAML or TOML) or languages like JavaScript, JSON does not support comments. You cannot use // or /* */ anywhere in a JSON file.
If you are using a JSON file for configuration and desperately need comments, you have a few options:
- Use a format that supports comments, like YAML, JSON5, or JSONC (JSON with Comments). Be aware that your parser must specifically support these formats.
- Add a dedicated key for comments within your object, such as
"_comment": "This is a configuration for the database."
2. Including Functions or Dates
JSON is a data serialization format, not a programming language. You cannot include functions, methods, or actual Date objects in JSON.
If you need to represent a date, you should convert it to a string format. The ISO 8601 format is the standard and widely recommended choice for dates in JSON (e.g., "2026-07-27T05:47:13Z").
3. Sending Undefined Values
The value undefined is not valid JSON. If a property has no value, you should either use the null literal or omit the key entirely from the object.
Tools of the Trade
You don't have to manage JSON formatting entirely on your own. There is a robust ecosystem of tools designed to make working with JSON easier.
- Prettier: An opinionated code formatter that works excellently with JSON, ensuring consistent indentation and fixing basic formatting errors automatically.
- jq: A lightweight and flexible command-line JSON processor. It is an indispensable tool for slicing, filtering, mapping, and transforming JSON data in the terminal.
- JSONLint: A popular online validator and reformatter for JSON. If you have a block of JSON that is failing to parse, pasting it into a linter will quickly highlight the exact line and character causing the issue.
- IDE Extensions: Modern editors like VS Code, IntelliJ, and WebStorm have built-in support for validating and formatting JSON files on save.
Conclusion
JSON has achieved its dominance in the development world for a reason: it perfectly balances human readability with machine efficiency. By understanding its core syntax, strictly adhering to its formatting rules (remember: double quotes and no trailing commas!), and applying best practices for readability, you can ensure your data exchanges are seamless.
Mastering JSON formatting is a foundational skill for any developer. Equip yourself with the right tools, keep your data structures clean, and you'll find that working with JSON is a breeze rather than a bottleneck. Happy coding!