JSON Formatter & Validator
Format, validate, and minify JSON. Perfect for debugging configs, API responses, and IaC files.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read and write, and easy for machines to parse and generate. JSON is language-independent and is widely used for data exchange in web applications, APIs, and configuration files. Many cloud infrastructure tools also support YAML format, which offers better readability for complex configurations.
Why JSON Formatting Matters
- Readability: Properly formatted JSON is easier to read and debug
- Maintainability: Well-formatted JSON is easier to maintain and modify
- Error detection: Formatting helps identify syntax errors
- Version control: Consistent formatting improves diff readability
- API documentation: Formatted JSON is essential for API docs
- Configuration files: Infrastructure as Code (IaC) files benefit from formatting
JSON Syntax Basics
Basic Structure
JSON supports two main data structures:
Objects (key-value pairs):
{
"key": "value",
"number": 42,
"boolean": true
}Arrays (ordered lists):
[
"item1",
"item2",
"item3"
]Data Types
JSON supports these data types:
| Type | Example | Notes |
|---|---|---|
| String | "hello" | Must be in double quotes |
| Number | 42, 3.14, -10 | No leading zeros, no NaN/Infinity |
| Boolean | true, false | Lowercase only |
| Null | null | Lowercase only |
| Object | {"key": "value"} | Unordered key-value pairs |
| Array | [1, 2, 3] | Ordered list of values |
Syntax Rules
- Keys must be strings: Always in double quotes
- No trailing commas: Last item in object/array cannot have a comma
- No comments: JSON does not support comments
- Double quotes only: Single quotes are not valid
- No functions: JSON cannot represent functions or undefined
JSON Formatting
Indentation
Indentation makes JSON readable by showing the hierarchy:
No indentation (minified):
{"name":"John","age":30,"city":"New York","hobbies":["reading","coding"],"address":{"street":"123 Main St","zip":"10001"}}2-space indentation (common):
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": [
"reading",
"coding"
],
"address": {
"street": "123 Main St",
"zip": "10001"
}
}4-space indentation:
{
"name": "John",
"age": 30,
"city": "New York",
"hobbies": [
"reading",
"coding"
],
"address": {
"street": "123 Main St",
"zip": "10001"
}
}Common Indentation Styles
2 spaces (most common):
- Used by: npm, many JavaScript projects
- Good balance between readability and file size
4 spaces:
- Used by: Some Python projects, older JavaScript projects
- More visual separation
Tabs:
- Less common in JSON
- Can cause issues with different tab sizes
No indentation (minified):
- Used for: Production APIs, reducing file size
- Not human-readable but efficient
JSON Minification
What is Minification?
Minification removes all unnecessary whitespace from JSON to reduce file size:
Before (formatted):
{
"name": "John",
"age": 30,
"city": "New York"
}After (minified):
{"name":"John","age":30,"city":"New York"}When to Minify
Minify for:
- Production APIs (reduces bandwidth)
- Large JSON files (saves storage)
- Network transmission (faster transfer)
- Embedded JSON in HTML/JavaScript
Don't minify for:
- Configuration files (readability matters)
- Development/debugging (need readability)
- Documentation (must be readable)
- Version control (better diffs when formatted)
Size Comparison
Example:
- Formatted: 1,234 characters
- Minified: 856 characters
- Savings: ~30% reduction
For large JSON files, minification can significantly reduce size.
JSON Validation
Common JSON Errors
1. Trailing Comma
Error:
{
"name": "John",
"age": 30, // ❌ Trailing comma
}Fixed:
{
"name": "John",
"age": 30 // ✅ No trailing comma
}2. Single Quotes
Error:
{
'name': 'John' // ❌ Single quotes
}Fixed:
{
"name": "John" // ✅ Double quotes
}3. Unquoted Keys
Error:
{
name: "John" // ❌ Unquoted key
}Fixed:
{
"name": "John" // ✅ Quoted key
}4. Comments
Error:
{
"name": "John",
// This is a comment // ❌ Comments not allowed
"age": 30
}Fixed:
{
"name": "John",
"age": 30
}5. Undefined/NaN/Infinity
Error:
{
"value": undefined, // ❌ Not valid
"number": NaN, // ❌ Not valid
"inf": Infinity // ❌ Not valid
}Fixed:
{
"value": null, // ✅ Use null
"number": null, // ✅ Use null or omit
"inf": null // ✅ Use null or omit
}6. Missing Quotes in Strings
Error:
{
"message": Hello World // ❌ Missing quotes
}Fixed:
{
"message": "Hello World" // ✅ Quoted string
}Validation Best Practices
- Validate early: Check JSON before processing
- Use proper error messages: Include line/column numbers
- Handle edge cases: Empty strings, null values, etc.
- Test with malformed JSON: Ensure robust error handling
Common Use Cases
1. API Response Formatting
Unformatted API response:
{"status":"success","data":{"users":[{"id":1,"name":"John","email":"john@example.com"},{"id":2,"name":"Jane","email":"jane@example.com"}]}}Formatted for readability:
{
"status": "success",
"data": {
"users": [
{
"id": 1,
"name": "John",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane",
"email": "jane@example.com"
}
]
}
}2. Configuration Files
Terraform variables:
{
"region": "us-east-1",
"instance_type": "t3.medium",
"tags": {
"Environment": "production",
"Project": "web-app"
}
}Kubernetes ConfigMap:
{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {
"name": "app-config"
},
"data": {
"database_url": "postgresql://localhost:5432/mydb",
"redis_url": "redis://localhost:6379"
}
}3. Package.json Formatting
Before:
{"name":"my-app","version":"1.0.0","dependencies":{"express":"^4.18.0","lodash":"^4.17.21"},"scripts":{"start":"node server.js","test":"jest"}}After:
{
"name": "my-app",
"version": "1.0.0",
"dependencies": {
"express": "^4.18.0",
"lodash": "^4.17.21"
},
"scripts": {
"start": "node server.js",
"test": "jest"
}
}4. AWS CloudFormation Templates
Formatted template:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"MyBucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "my-unique-bucket-name",
"VersioningConfiguration": {
"Status": "Enabled"
}
}
}
}
}5. Log File Analysis
JSON logs often include timestamps in various formats. Use our Unix timestamp converter to convert between ISO 8601 dates and Unix timestamps.
Minified log entry:
{"timestamp":"2024-01-01T12:00:00Z","level":"error","message":"Database connection failed","service":"api","request_id":"abc123"}Formatted for debugging:
{
"timestamp": "2024-01-01T12:00:00Z",
"level": "error",
"message": "Database connection failed",
"service": "api",
"request_id": "abc123"
}Formatting in Different Languages
JavaScript/TypeScript
Format:
const json = '{"name":"John","age":30}';
const formatted = JSON.stringify(JSON.parse(json), null, 2);
console.log(formatted);Minify:
const json = '{"name": "John", "age": 30}';
const minified = JSON.stringify(JSON.parse(json));
console.log(minified);Validate:
function validateJson(json) {
try {
JSON.parse(json);
return { valid: true };
} catch (e) {
return { valid: false, error: e.message };
}
}Python
Format:
import json
json_str = '{"name":"John","age":30}'
parsed = json.loads(json_str)
formatted = json.dumps(parsed, indent=2)
print(formatted)Minify:
import json
json_str = '{"name": "John", "age": 30}'
parsed = json.loads(json_str)
minified = json.dumps(parsed, separators=(',', ':'))
print(minified)Validate:
import json
def validate_json(json_str):
try:
json.loads(json_str)
return {'valid': True}
except json.JSONDecodeError as e:
return {'valid': False, 'error': str(e)}Command Line (jq)
Format:
echo '{"name":"John","age":30}' | jq .Minify:
echo '{"name": "John", "age": 30}' | jq -c .Validate:
echo '{"name":"John"}' | jq . > /dev/null && echo "Valid" || echo "Invalid"Command Line (Python)
Format:
python -m json.tool input.json > output.jsonMinify:
python -c "import json, sys; print(json.dumps(json.load(sys.stdin), separators=(',',':')))" < input.jsonBest Practices
1. Consistent Indentation
Choose one style and stick with it:
- 2 spaces (most common)
- 4 spaces
- Tabs (less common)
Don't mix styles within the same project.
2. Key Ordering
For objects:
- Alphabetical ordering (easier to find keys)
- Logical grouping (related keys together)
- Important keys first (id, name, type)
Example:
{
"id": 1,
"name": "John",
"email": "john@example.com",
"metadata": {
"created_at": "2024-01-01",
"updated_at": "2024-01-02"
}
}3. Array Formatting
Short arrays (inline):
{
"tags": ["javascript", "json", "formatting"]
}Long arrays (multiline):
{
"users": [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"},
{"id": 3, "name": "Bob"}
]
}4. String Escaping
Escape special characters:
{
"message": "He said \"Hello\"",
"path": "C:\\Users\\Name",
"newline": "Line 1\nLine 2"
}5. Null vs Omission
Use null for explicit absence:
{
"name": "John",
"middle_name": null // Explicitly no middle name
}Omit for optional fields:
{
"name": "John"
// middle_name omitted if not applicable
}Performance Considerations
File Size Impact
Formatted JSON:
- Larger file size (whitespace)
- Better for human reading
- Better for version control diffs
Minified JSON:
- Smaller file size (~20-30% reduction)
- Faster network transfer
- Better for production APIs
Parsing Performance
Parsing speed:
- Minified JSON: Slightly faster (less characters to parse)
- Formatted JSON: Slightly slower (more characters)
- Difference is usually negligible
For large files (>1MB):
- Consider minification for production
- Format for development/debugging
Common Mistakes to Avoid
1. Manual Formatting
Don't manually format large JSON files:
- Error-prone
- Time-consuming
- Inconsistent
Use tools:
- JSON formatters
- Editor plugins
- Command-line tools
2. Inconsistent Formatting
Problem:
{
"key1": "value1",
"key2": "value2", // Inconsistent indentation
"key3": "value3"
}Solution: Use automated formatting tools to maintain consistency.
3. Not Validating Before Formatting
Always validate JSON before formatting:
- Formatting invalid JSON won't fix errors
- May hide syntax errors
- Can cause confusion
4. Formatting Production APIs
Don't format JSON in production APIs:
- Increases response size
- Slows down transmission
- Wastes bandwidth
Minify for production, format for development.
5. Mixing JSON and JavaScript
Don't confuse JSON with JavaScript objects:
// JavaScript (not JSON)
const obj = {
name: 'John', // No quotes needed
age: 30,
// Comments allowed
};
// JSON (must be valid)
const json = '{"name":"John","age":30}'; // Quotes required, no commentsTools and Libraries
Online Tools
- JSON Formatter & Validator: Format, validate, and minify JSON
- JSONLint: Validate and format JSON
- JSON Editor Online: Visual JSON editor
Editor Plugins
VS Code:
- Prettier (automatic formatting)
- JSON Tools
- JSON Editor
Sublime Text:
- Pretty JSON
- JSONLint
Vim:
- vim-json
- jq.vim
Command-Line Tools
jq (most popular):
# Format
jq . file.json
# Minify
jq -c . file.json
# Validate
jq . file.json > /dev/nullPython json.tool:
python -m json.tool file.jsonNode.js:
node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync(0)), null, 2))"Frequently Asked Questions
What's the difference between JSON and JavaScript objects?
JSON:
- String format
- Keys must be quoted
- No functions, undefined, or comments
- Language-independent
JavaScript objects:
- Native data type
- Keys don't need quotes (unless special characters)
- Can contain functions, undefined
- JavaScript-specific
Can JSON have comments?
No. JSON does not support comments. If you need comments, consider:
- Using a separate documentation file
- Adding a
_commentfield (not standard) - Using JSON5 or JSONC (extensions with comment support)
Should I format JSON in production?
Generally no. Minify JSON for production to:
- Reduce file size
- Improve transmission speed
- Save bandwidth
Format JSON for:
- Development
- Debugging
- Documentation
- Configuration files
How do I handle large JSON files?
For very large files (>100MB):
- Consider streaming parsers
- Use JSONL (JSON Lines) format
- Split into multiple files
- Use binary formats (MessagePack, BSON)
What's the maximum JSON size?
No official limit, but practical limits:
- Browsers: ~100-500MB (varies)
- Node.js: Limited by available memory
- APIs: Usually 1-10MB (check API limits)
Can JSON have duplicate keys?
Technically yes, but behavior is undefined:
{
"name": "John",
"name": "Jane" // Duplicate key - behavior undefined
}Best practice: Don't use duplicate keys. Most parsers will use the last value.
How do I format JSON with custom indentation?
JavaScript:
JSON.stringify(obj, null, 4); // 4 spaces
JSON.stringify(obj, null, '\t'); // TabsPython:
json.dumps(obj, indent=4) # 4 spaces
json.dumps(obj, indent='\t') # Tabs