JSON (JavaScript Object Notation) has become the universal language of data exchange on the web. Whether you're building APIs, storing configuration files, or exchanging data between services, understanding how to properly format JSON is an essential skill for every developer.
In this comprehensive guide, we'll cover everything you need to know about JSON formatting - from basic syntax rules to advanced techniques used by professional developers. By the end, you'll be a JSON formatting expert!
Table of Contents
- What is JSON?
- JSON Syntax Rules
- JSON Data Types
- How to Format JSON Online
- Format JSON in JavaScript
- Format JSON in Python
- JSON Formatting Best Practices
- Common JSON Errors and How to Fix Them
- Best JSON Formatting Tools
What is JSON?
JSON stands for JavaScript Object Notation. It's a lightweight, text-based data format that is easy for humans to read and write, and easy for machines to parse and generate. JSON was derived from JavaScript but is language-independent, making it the preferred format for data interchange in web applications.
Here's a simple example of JSON data representing a user:
{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com",
"isActive": true,
"roles": ["admin", "user"],
"address": {
"street": "123 Main St",
"city": "New York",
"zipCode": "10001"
}
}
Why is JSON So Popular?
JSON has become the dominant data format for several reasons:
- Human Readable: Unlike binary formats, JSON is text-based and easy to read
- Language Independent: Every major programming language has JSON support
- Lightweight: JSON has minimal syntax overhead compared to XML
- Native JavaScript Support: JSON works seamlessly with JavaScript objects
- REST API Standard: Most modern REST APIs use JSON for data exchange
JSON Syntax Rules
Understanding JSON syntax is fundamental to formatting JSON correctly. Here are the essential rules you must follow:
1. Key-Value Pairs
JSON data is organized as key-value pairs. Keys must be strings enclosed in double quotes:
{
"name": "Alice",
"age": 25
}
Important: Single quotes are NOT valid in JSON. This is a common mistake when developers come from JavaScript:
// β WRONG - Single quotes
{'name': 'Alice'}
// β
CORRECT - Double quotes
{"name": "Alice"}
2. Colons and Commas
Use colons (:) to separate keys from values, and commas (,) to separate key-value pairs:
{
"firstName": "John",
"lastName": "Doe",
"age": 30
}
Common Error: Trailing commas (a comma after the last item) are NOT allowed in JSON:
// β WRONG - Trailing comma
{
"name": "Alice",
"age": 25, // This comma will cause an error!
}
// β
CORRECT - No trailing comma
{
"name": "Alice",
"age": 25
}
3. Curly Braces for Objects
Objects are enclosed in curly braces {}. An object contains zero or more key-value pairs:
{
"user": {
"id": 1,
"name": "John",
"profile": {
"avatar": "https://example.com/avatar.jpg",
"bio": "Developer"
}
}
}
4. Square Brackets for Arrays
Arrays are enclosed in square brackets [] and can contain any JSON values:
{
"fruits": ["apple", "banana", "orange"],
"numbers": [1, 2, 3, 4, 5],
"users": [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]
}
JSON Data Types
JSON supports six data types. Understanding these is crucial for proper JSON formatting:
1. Strings
Text enclosed in double quotes:
{"message": "Hello, World!"}
2. Numbers
Integer or floating-point numbers (no quotes):
{
"integer": 42,
"decimal": 3.14,
"negative": -100,
"scientific": 1.5e10
}
3. Booleans
Either true or false (lowercase, no quotes):
{
"isActive": true,
"isDeleted": false
}
4. Null
Represents empty or missing value (lowercase, no quotes):
{"middleName": null}
5. Objects
Nested key-value pairs in curly braces:
{
"address": {
"street": "123 Main St",
"city": "NYC"
}
}
6. Arrays
Ordered list of values in square brackets:
{"tags": ["javascript", "json", "tutorial"]}
How to Format JSON Online
The fastest way to format JSON is using an online JSON formatter. Here's how to use JSON Formatter Pro:
Step-by-Step Guide
- Open the Tool: Navigate to JSON Formatter Pro
- Paste Your JSON: Copy your unformatted JSON and paste it into the left editor panel
- Click Format: Press the "Format" button to beautify your JSON
- Copy or Download: Use the copy button or download the formatted file
Example: Formatting Minified JSON
Before (minified/compressed JSON):
{"users":[{"id":1,"name":"Alice","email":"alice@example.com"},{"id":2,"name":"Bob","email":"bob@example.com"}],"total":2}
After (formatted/beautified JSON):
{
"users": [
{
"id": 1,
"name": "Alice",
"email": "alice@example.com"
},
{
"id": 2,
"name": "Bob",
"email": "bob@example.com"
}
],
"total": 2
}
Format JSON in JavaScript
JavaScript provides built-in methods for working with JSON. Here's how to format JSON programmatically:
Using JSON.stringify()
The JSON.stringify() method converts a JavaScript object to a JSON string. The key to formatting is the third parameter for indentation:
// Create a JavaScript object
const user = {
name: "John Doe",
age: 30,
skills: ["JavaScript", "Python", "SQL"],
address: {
city: "New York",
country: "USA"
}
};
// Convert to formatted JSON string (2-space indentation)
const formattedJson = JSON.stringify(user, null, 2);
console.log(formattedJson);
// Output:
// {
// "name": "John Doe",
// "age": 30,
// "skills": [
// "JavaScript",
// "Python",
// "SQL"
// ],
// "address": {
// "city": "New York",
// "country": "USA"
// }
// }
Indentation Options
// 2 spaces (common)
JSON.stringify(obj, null, 2);
// 4 spaces
JSON.stringify(obj, null, 4);
// Tab character
JSON.stringify(obj, null, '\t');
// No formatting (minified)
JSON.stringify(obj);
Using a Replacer Function
The second parameter can filter or transform values:
const user = {
name: "Alice",
password: "secret123",
email: "alice@example.com"
};
// Remove sensitive fields
const safeJson = JSON.stringify(user, (key, value) => {
if (key === 'password') return undefined;
return value;
}, 2);
// Output excludes password field
Parsing JSON in JavaScript
// Parse JSON string to object
const jsonString = '{"name": "Alice", "age": 25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "Alice"
console.log(obj.age); // 25
// Handle parse errors
try {
const data = JSON.parse(invalidJson);
} catch (error) {
console.error('Invalid JSON:', error.message);
}
Format JSON in Python
Python's json module provides comprehensive JSON formatting capabilities:
Basic Formatting with json.dumps()
import json
# Python dictionary
data = {
"name": "John Doe",
"age": 30,
"skills": ["Python", "JavaScript", "SQL"],
"address": {
"city": "New York",
"country": "USA"
}
}
# Format with 2-space indentation
formatted = json.dumps(data, indent=2)
print(formatted)
# Format with 4-space indentation
formatted = json.dumps(data, indent=4)
# Sort keys alphabetically
formatted = json.dumps(data, indent=2, sort_keys=True)
Reading and Formatting JSON Files
import json
# Read JSON file
with open('data.json', 'r') as file:
data = json.load(file)
# Write formatted JSON to file
with open('formatted.json', 'w') as file:
json.dump(data, file, indent=2)
# One-liner to format a JSON file
def format_json_file(input_path, output_path):
with open(input_path) as f:
data = json.load(f)
with open(output_path, 'w') as f:
json.dump(data, f, indent=2)
Handling Special Characters
import json
data = {"message": "Hello, δΈη!", "emoji": "π"}
# Default: escape non-ASCII characters
print(json.dumps(data))
# {"message": "Hello, \u4e16\u754c!", "emoji": "\ud83c\udf89"}
# Preserve Unicode characters
print(json.dumps(data, ensure_ascii=False))
# {"message": "Hello, δΈη!", "emoji": "π"}
Pretty Print with pprint
import json
from pprint import pprint
data = json.loads('{"users": [{"id": 1}, {"id": 2}]}')
# Standard pprint (Python syntax)
pprint(data)
# For JSON output, use json.dumps
print(json.dumps(data, indent=2))
JSON Formatting Best Practices
1. Use Consistent Indentation
Choose either 2 or 4 spaces and stick with it throughout your project. Tabs work but spaces are more universally supported.
2. Use Descriptive Key Names
// β Poor naming
{"fn": "John", "ln": "Doe", "a": 30}
// β
Descriptive naming
{"firstName": "John", "lastName": "Doe", "age": 30}
3. Use camelCase for Keys
Follow JavaScript conventions with camelCase:
{
"firstName": "John",
"lastName": "Doe",
"dateOfBirth": "1990-01-15",
"isEmailVerified": true
}
4. Keep JSON Flat When Possible
Avoid deeply nested structures when a flatter structure works:
// β Too nested
{
"user": {
"profile": {
"details": {
"name": "John"
}
}
}
}
// β
Flatter structure
{
"userName": "John",
"userEmail": "john@example.com"
}
5. Validate Before Sending
Always validate JSON before sending it to APIs or storing it:
function isValidJson(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
Common JSON Errors and How to Fix Them
1. Trailing Commas
// β Error: Trailing comma
{"name": "Alice", "age": 25,}
// β
Fixed
{"name": "Alice", "age": 25}
2. Single Quotes
// β Error: Single quotes
{'name': 'Alice'}
// β
Fixed: Use double quotes
{"name": "Alice"}
3. Unquoted Keys
// β Error: Unquoted key
{name: "Alice"}
// β
Fixed: Quote the key
{"name": "Alice"}
4. Comments (Not Allowed)
// β Error: Comments not allowed in JSON
{
"name": "Alice", // This is a comment
"age": 25
}
// β
Fixed: Remove comments
{
"name": "Alice",
"age": 25
}
5. Undefined Values
// β Error: undefined is not valid
{"value": undefined}
// β
Use null instead
{"value": null}
Best JSON Formatting Tools
Online Tools
- JSON Formatter Pro: Free online formatter with validation, minification, and conversion
- JSONLint: Simple online validator and formatter
- JSON Editor Online: Visual tree editor for JSON
IDE Extensions
- VS Code: Built-in JSON formatting (Shift+Alt+F)
- JetBrains IDEs: Built-in JSON formatting and validation
- Sublime Text: Pretty JSON package
Command Line Tools
# jq - Powerful command-line JSON processor
cat data.json | jq .
# python - One-liner formatting
python -m json.tool data.json
# Node.js
node -e "console.log(JSON.stringify(require('./data.json'), null, 2))"
Conclusion
JSON formatting is an essential skill for modern developers. Whether you're debugging API responses, working with configuration files, or building web applications, properly formatted JSON makes your life easier.
Key takeaways:
- Always use double quotes for keys and string values
- Never use trailing commas
- Use consistent 2 or 4-space indentation
- Validate JSON before sending or storing it
- Use online tools like JSON Formatter Pro for quick formatting
Start practicing with our free JSON Formatter tool and become a JSON formatting expert today!