JSON Best Practices: Tips for Writing Better JSON
Learn essential JSON best practices to write clean, maintainable, and efficient JSON code. This guide covers naming conventions, security tips, performance optimization, and more.
1. Naming Conventions
Use camelCase for Keys
The most common convention in JSON is to use camelCase for property names, especially in JavaScript environments:
{
"firstName": "John",
"lastName": "Doe",
"emailAddress": "john@example.com",
"phoneNumber": "+1234567890"
}
Use snake_case for Database Integration
If your JSON directly maps to database columns, snake_case might be more appropriate:
{
"first_name": "John",
"last_name": "Doe",
"email_address": "john@example.com",
"created_at": "2025-01-20T10:00:00Z"
}
2. Data Type Best Practices
Use Appropriate Data Types
Always use the correct data type for your values:
// Good ✓
{
"age": 25,
"price": 19.99,
"isActive": true,
"tags": ["json", "tutorial"],
"metadata": null
}
// Bad ✗
{
"age": "25", // Should be number
"price": "19.99", // Should be number
"isActive": "true", // Should be boolean
"tags": "json,tutorial", // Should be array
"metadata": "null" // Should be null
}
Avoid Redundant Nesting
Keep your JSON structure flat when possible:
// Good ✓
{
"userId": 123,
"userName": "john_doe",
"userEmail": "john@example.com"
}
// Overcomplicated ✗
{
"user": {
"data": {
"information": {
"id": 123,
"name": "john_doe"
}
}
}
}
3. Security Best Practices
Don't Store Sensitive Data
Avoid including sensitive information in JSON responses:
// Bad ✗
{
"user": {
"id": 123,
"email": "john@example.com",
"password": "mypassword123", // NEVER do this!
"apiKey": "secret-key-xyz" // NEVER do this!
}
}
// Good ✓
{
"user": {
"id": 123,
"email": "john@example.com",
"hasPassword": true
}
}
Validate All Input
Always validate JSON input before processing:
// JavaScript validation example
function validateUserData(data) {
if (!data.email || !data.email.includes('@')) {
throw new Error('Invalid email');
}
if (typeof data.age !== 'number' || data.age < 0) {
throw new Error('Invalid age');
}
return true;
}
4. Performance Optimization
Minimize JSON Size
Remove unnecessary whitespace in production:
// Development (readable)
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
// Production (minified)
{"name":"John Doe","age":30,"city":"New York"}
Use Pagination for Large Datasets
Instead of returning all data at once, use pagination:
{
"data": [...],
"pagination": {
"currentPage": 1,
"totalPages": 10,
"pageSize": 20,
"totalItems": 200
}
}
5. Error Handling
Include Clear Error Messages
Provide structured error information:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email address",
"field": "email",
"timestamp": "2025-01-20T10:00:00Z"
}
}
6. Documentation and Versioning
Version Your API Responses
Include version information in your JSON responses:
{
"version": "2.0",
"data": {
"users": [...]
}
}
7. Common Mistakes to Avoid
- Using trailing commas (not valid in JSON)
- Using single quotes instead of double quotes
- Forgetting to escape special characters
- Using undefined or functions (not valid in JSON)
- Creating circular references
Invalid JSON Examples
// Invalid: Trailing comma
{
"name": "John",
"age": 30, ← Trailing comma
}
// Invalid: Single quotes
{
'name': 'John' ← Must use double quotes
}
// Invalid: Unescaped characters
{
"text": "Line 1
Line 2" ← Must escape newline
}
Summary
Following these JSON best practices will help you:
- Write more maintainable and readable JSON
- Improve application performance
- Enhance security and reduce vulnerabilities
- Make your APIs easier to use and understand
- Reduce bugs and parsing errors