JSON Best Practices: Formatting, Validation & Parsing
ยท 8 min read
JSON Fundamentals
JSON (JavaScript Object Notation) is the most widely used data interchange format on the web. It's human-readable, language-independent, and supported by virtually every programming language. Understanding JSON best practices is essential for building reliable APIs, configuration files, and data pipelines.
JSON supports six data types:
{
"string": "Hello, World!",
"number": 42,
"decimal": 3.14,
"boolean": true,
"null_value": null,
"array": [1, 2, 3],
"object": {"nested": "value"}
}
Important: JSON does not support comments, trailing commas, single quotes, undefined, functions, or dates (dates must be strings, typically ISO 8601 format).
๐ ๏ธ Format and validate your JSON
Formatting Standards
Consistent formatting makes JSON readable and maintainable. Follow these standards:
Use 2-Space Indentation
// โ
Good: 2-space indentation
{
"user": {
"name": "Jane",
"email": "[email protected]"
}
}
// โ Bad: No indentation
{"user":{"name":"Jane","email":"[email protected]"}}
Use camelCase for Keys
// โ
Good: camelCase
{
"firstName": "Jane",
"lastName": "Smith",
"emailAddress": "[email protected]",
"createdAt": "2026-03-15T10:30:00Z"
}
// โ Avoid mixing styles
{
"first_name": "Jane", // snake_case
"LastName": "Smith", // PascalCase
"email-address": "..." // kebab-case
}
Use ISO 8601 for Dates
{
"createdAt": "2026-03-15T10:30:00Z",
"updatedAt": "2026-03-15T14:45:00+08:00",
"date": "2026-03-15"
}
Use Meaningful Key Names
// โ
Good: Descriptive keys
{
"totalItemCount": 42,
"isActive": true,
"errorMessage": "Invalid email format"
}
// โ Bad: Cryptic abbreviations
{
"tic": 42,
"ia": true,
"em": "Invalid email format"
}
Validation Techniques
Always validate JSON before processing it. Here are multiple approaches:
Online Validation
Paste your JSON into our JSON Formatter for instant validation with clear error messages showing exactly where the problem is.
Command Line Validation
# Using jq (recommended)
echo '{"name": "test"}' | jq .
# Pretty-printed output = valid JSON
echo '{"name": invalid}' | jq .
# Error: parse error at line 1, column 15
# Using Python
echo '{"name": "test"}' | python3 -m json.tool
# Using Node.js
node -e "JSON.parse(require('fs').readFileSync('data.json'))"
JSON Schema Validation
JSON Schema defines the structure your JSON should have. Use it for API request/response validation:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
}
}
}
Parsing JSON in JavaScript
// Parse JSON string to object
const data = JSON.parse('{"name": "Jane", "age": 30}');
console.log(data.name); // "Jane"
// Safe parsing with error handling
function safeJsonParse(str) {
try {
return { data: JSON.parse(str), error: null };
} catch (e) {
return { data: null, error: e.message };
}
}
const result = safeJsonParse('invalid json');
if (result.error) {
console.error('Parse failed:', result.error);
}
// Stringify object to JSON
const json = JSON.stringify({ name: 'Jane' });
// '{"name":"Jane"}'
// Pretty print with 2-space indentation
const pretty = JSON.stringify({ name: 'Jane', age: 30 }, null, 2);
// Custom serialization with replacer
const filtered = JSON.stringify(data, (key, value) => {
if (key === 'password') return undefined; // Exclude passwords
return value;
}, 2);
// Custom deserialization with reviver
const withDates = JSON.parse(jsonString, (key, value) => {
if (key === 'createdAt') return new Date(value);
return value;
});
Parsing JSON in Python
import json
# Parse JSON string
data = json.loads('{"name": "Jane", "age": 30}')
print(data['name']) # "Jane"
# Parse JSON file
with open('data.json', 'r') as f:
data = json.load(f)
# Safe parsing
def safe_json_parse(s):
try:
return json.loads(s), None
except json.JSONDecodeError as e:
return None, str(e)
# Write JSON to file
with open('output.json', 'w') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# Pretty print
print(json.dumps(data, indent=2, sort_keys=True))
# Custom serialization for non-serializable types
from datetime import datetime
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json.dumps({"created": datetime.now()}, cls=DateEncoder)
Common JSON Mistakes
- Trailing commas: JSON doesn't allow trailing commas after the last item.
// โ Invalid {"items": [1, 2, 3,]} // โ Valid {"items": [1, 2, 3]} - Single quotes: JSON requires double quotes for strings and keys.
// โ Invalid {'name': 'Jane'} // โ Valid {"name": "Jane"} - Comments: JSON doesn't support comments. Use JSONC or JSON5 if you need them.
// โ Invalid JSON { "name": "Jane" // This is a comment } // โ Store comments as data if needed { "_comment": "User configuration", "name": "Jane" } - Unquoted keys: All keys must be quoted strings.
// โ Invalid {name: "Jane"} // โ Valid {"name": "Jane"} - Number precision: JSON numbers follow IEEE 754. Large integers (>2^53) lose precision. Use strings for big numbers:
{ "id": "9007199254740993", "amount": "99999999999999.99" }
Performance Optimization
- Minify for production. Remove whitespace from JSON sent over the network. This reduces payload size by 10-30%. Tools:
JSON.stringify(data)(no indent) orjq -c. - Use streaming parsers for large files. Don't load a 500MB JSON file into memory. Use streaming parsers like
JSONStream(Node.js) orijson(Python). - Compress responses. Enable gzip/brotli compression on your server. JSON compresses extremely well (often 80-90% reduction).
- Use consistent key ordering. Sorted keys improve gzip compression because repeated patterns are more predictable.
- Consider alternatives for large datasets. For large data transfers, consider CSV (tabular data), Protocol Buffers (typed schemas), or MessagePack (binary JSON).
Frequently Asked Questions
What's the difference between JSON and JavaScript objects?
JSON is a text format โ all keys must be double-quoted strings, and values can only be strings, numbers, booleans, null, arrays, or objects. JavaScript objects are runtime data structures that support functions, undefined, symbols, and unquoted keys.
Can JSON have comments?
No, standard JSON does not support comments. If you need comments, use JSONC (JSON with Comments) or JSON5. Some tools like VS Code support JSONC for configuration files.
What is the maximum size of a JSON file?
The JSON specification has no size limit. However, practical limits depend on available memory and the parser. Most web APIs limit request bodies to 1-10MB. For larger data, consider streaming or pagination.
How do I convert JSON to CSV?
For flat JSON arrays, use tools like jq, Python's csv module, or online converters. Use our CSV Viewer to inspect the result. For nested JSON, flatten the structure first.