How to Format JSON: Pretty Print and Beautify Guide 2026
Learn how to format and beautify JSON using command-line tools, code editors, online formatters, and programming languages. Complete guide with examples.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
# How to Format JSON: Pretty Print and Beautify Guide
Formatting JSON properly is essential for readability and debugging. Whether you're working with API responses, configuration files, or data exports, this comprehensive guide will show you every method to format and beautify JSON in 2026.
Why Format JSON?
Readability
Minified (hard to read):{"name":"John","age":30,"address":{"street":"123 Main St","city":"NYC"},"hobbies":["reading","coding"]}
Formatted (easy to read):
{
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "NYC"
},
"hobbies": [
"reading",
"coding"
]
}
Debugging
Formatted JSON makes it easier to:
- Spot syntax errors
- Identify missing commas
- Verify data structure
- Track down issues
Version Control
Properly formatted JSON produces cleaner diffs in Git.
Method 1: Online JSON Formatters
Big JSON Viewer
Fast, handles large files:
JSONLint
Validates and formats:
JSON Formatter
Simple and quick:
Method 2: Command Line Tools
Using jq
The most powerful command-line JSON processor:
# Format JSON file
jq . input.json
# Format and save
jq . input.json > formatted.json
# Format with 4-space indentation
jq --indent 4 . input.json
# Format from API response
curl https://api.example.com/data | jq .
# Compact (minify)
jq -c . input.json
Installation:
# macOS
brew install jq
# Ubuntu/Debian
sudo apt-get install jq
# Windows (with Chocolatey)
choco install jq
Using Python
Built-in tool:
# Format JSON file (2-space indent)
python -m json.tool input.json
# Format with custom indent
python -m json.tool --indent 4 input.json > formatted.json
# Format from stdin
echo '{"name":"John","age":30}' | python -m json.tool
Using Node.js
Quick one-liner:
# Format JSON file
node -e "console.log(JSON.stringify(require('./input.json'), null, 2))"
# From string
node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 2))" '{"a":1,"b":2}'
Method 3: Code Editors
Visual Studio Code
Built-in Formatter:Shift + Alt + F (Windows/Linux)Shift + Option + F (Mac){
"editor.formatOnSave": true,
"editor.tabSize": 2,
"[json]": {
"editor.defaultFormatter": "vscode.json-language-features",
"editor.formatOnSave": true
}
}
Command Palette:
Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (Mac)Sublime Text
Using Package:Ctrl + Alt + J to formatVim
Using built-in::%!jq .
Or with Python:
:%!python -m json.tool
Method 4: Programming Languages
JavaScript/Node.js
// Format with 2-space indentation
const data = {name: "John", age: 30, city: "NYC"};
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// Format from string
const jsonString = '{"name":"John","age":30}';
const parsed = JSON.parse(jsonString);
const pretty = JSON.stringify(parsed, null, 2);
// Read file and format
const fs = require('fs');
const rawData = fs.readFileSync('input.json');
const jsonData = JSON.parse(rawData);
const formatted = JSON.stringify(jsonData, null, 2);
fs.writeFileSync('output.json', formatted);
Custom Indentation:
// 4 spaces
JSON.stringify(data, null, 4);
// Tab character
JSON.stringify(data, null, '\t');
// Custom string
JSON.stringify(data, null, ' ');
Python
import json
# Format dictionary
data = {"name": "John", "age": 30, "city": "NYC"}
formatted = json.dumps(data, indent=2)
print(formatted)
# Format from string
json_string = '{"name":"John","age":30}'
parsed = json.loads(json_string)
pretty = json.dumps(parsed, indent=2)
# Read and format file
with open('input.json', 'r') as f:
data = json.load(f)
with open('output.json', 'w') as f:
json.dump(data, f, indent=2)
# Sort keys alphabetically
formatted = json.dumps(data, indent=2, sort_keys=True)
# Ensure ASCII (escape unicode)
formatted = json.dumps(data, indent=2, ensure_ascii=True)
PHP
<?php
$data = array(
"name" => "John",
"age" => 30,
"city" => "NYC"
);
// Format with pretty print
$formatted = json_encode($data, JSON_PRETTY_PRINT);
echo $formatted;
// Additional options
$formatted = json_encode($data,
JSON_PRETTY_PRINT |
JSON_UNESCAPED_SLASHES |
JSON_UNESCAPED_UNICODE
);
// Read and format file
$jsonString = file_get_contents('input.json');
$data = json_decode($jsonString, true);
$formatted = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents('output.json', $formatted);
?>
Java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonFormatter {
public static void main(String[] args) {
// Create Gson instance with pretty printing
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
// Format object
Person person = new Person("John", 30);
String formatted = gson.toJson(person);
System.out.println(formatted);
// Format from string
String jsonString = "{\"name\":\"John\",\"age\":30}";
Object obj = gson.fromJson(jsonString, Object.class);
String pretty = gson.toJson(obj);
}
}
C#
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main()
{
// Format object
var person = new { Name = "John", Age = 30 };
string formatted = JsonConvert.SerializeObject(person,
Formatting.Indented);
Console.WriteLine(formatted);
// Format from string
string jsonString = "{\"name\":\"John\",\"age\":30}";
JObject obj = JObject.Parse(jsonString);
string pretty = obj.ToString(Formatting.Indented);
}
}
Method 5: Browser DevTools
Chrome/Edge DevTools
F12)Or use Console:
// Format in console
const data = '{"name":"John","age":30}';
console.log(JSON.parse(data));
// Or
copy(JSON.stringify(JSON.parse(data), null, 2));
// Then paste formatted JSON
Firefox DevTools
Similar to Chrome, with automatic JSON formatting in Network tab.
Advanced Formatting Options
Custom Replacer Function
const data = {
name: "John",
password: "secret123",
age: 30,
createdAt: new Date()
};
// Hide sensitive data and format dates
const formatted = JSON.stringify(data, (key, value) => {
if (key === 'password') return '';
if (value instanceof Date) return value.toISOString();
return value;
}, 2);
Sort Keys
function sortKeys(obj) {
if (typeof obj !== 'object' || obj === null) return obj;
if (Array.isArray(obj)) return obj.map(sortKeys);
return Object.keys(obj)
.sort()
.reduce((sorted, key) => {
sorted[key] = sortKeys(obj[key]);
return sorted;
}, {});
}
const formatted = JSON.stringify(sortKeys(data), null, 2);
Custom Indentation
import json
# Custom indent width
json.dumps(data, indent=4) # 4 spaces
# Tab indentation
json.dumps(data, indent='\t')
# Custom separator
json.dumps(data, indent=2, separators=(',', ': '))
Minify vs. Beautify
When to Minify
Production:
- Reduce file size
- Faster transmission
- Lower bandwidth costs
# Minify with jq
jq -c . input.json > minified.json
// Minify in JavaScript
JSON.stringify(data); // No spacing
When to Beautify
Development:
- Better readability
- Easier debugging
- Code review
Documentation:
- Examples in docs
- Configuration templates
Batch Formatting
Format Multiple Files
Bash script:
#!/bin/bash
for file in .json; do
jq . "$file" > "formatted_$file"
done
Python script:
import json
import os
import glob
for filepath in glob.glob('.json'):
with open(filepath, 'r') as f:
data = json.load(f)
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
Git Pre-commit Hook
Automatically format JSON before commit:
#!/bin/bash
# .git/hooks/pre-commit
for file in $(git diff --cached --name-only | grep -E '\.json$'); do
jq . "$file" > "$file.tmp" && mv "$file.tmp" "$file"
git add "$file"
done
Common Formatting Issues
Issue 1: Invalid JSON
Formatters will fail on invalid JSON:
{
"name": "John", // Comments not allowed
'age': 30, // Single quotes not allowed
"city": "NYC", // Trailing comma not allowed
}
Solution: Use a validator first (JSONLint, jq).
Issue 2: Large Files
Large files may crash online formatters.
Solution: Use command-line tools:jq . large-file.json > formatted.json
Issue 3: Character Encoding
Unicode characters may display incorrectly.
Solution: Ensure UTF-8 encoding:with open('file.json', 'r', encoding='utf-8') as f:
data = json.load(f)
Best Practices
1. Consistent Indentation
Choose 2 or 4 spaces and stick with it across your project.
2. Line Length
Keep lines under 80-120 characters when possible.
3. Alphabetical Keys
Sort keys alphabetically for easier comparison.
4. Format Before Commit
Always format JSON before committing to version control.
5. Use EditorConfig
# .editorconfig
[.json]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
Conclusion
Formatting JSON is a fundamental skill for developers. Whether you prefer online tools, command-line utilities, or programming language built-ins, there's a method that fits your workflow.
For quick tasks, use online formatters or browser DevTools. For automation and large files, use command-line tools like jq. For integration into your code, use language-specific JSON libraries.
Remember: formatted JSON is easier to read, debug, and maintain. Make formatting a habit in your development workflow.
Related Articles
Best JSON Online Tools 2026: Viewers, Validators, and Formatters
Comprehensive guide to the best JSON online tools. Compare viewers, validators, formatters, and converters for working with JSON data.
Python and JSON: Complete Guide to json Module
Master JSON in Python with the json module. Learn to parse, generate, and manipulate JSON data with practical examples and best practices.
JavaScript JSON: Parse, Stringify, and Best Practices
Complete guide to JSON in JavaScript. Learn JSON.parse(), JSON.stringify(), error handling, and advanced techniques for web development.