Back to Blog
🎓Tutorials

JSON Best Practices: Writing Better JSON

2024-01-2510 min readJSON Toolset Team
#JSON#best practices#guide#tips

JSON Best Practices

Follow these best practices to write clean, maintainable, and efficient JSON.

1. Use Consistent Naming

camelCase (Recommended for JavaScript)

{
  "firstName": "John",
  "lastName": "Doe",
  "emailAddress": "john@example.com"
}

snake_case (Common in Python)

{
  "first_name": "John",
  "last_name": "Doe",
  "email_address": "john@example.com"
}

Rule: Pick one style and stick to it!

2. Keep It Flat When Possible

❌ Too nested:

{
  "user": {
    "personal": {
      "name": {
        "first": "John",
        "last": "Doe"
      }
    }
  }
}

✅ Better:

{
  "user": {
    "firstName": "John",
    "lastName": "Doe"
  }
}

3. Use Arrays for Lists

✅ Good:

{
  "colors": ["red", "green", "blue"]
}

❌ Avoid:

{
  "color1": "red",
  "color2": "green",
  "color3": "blue"
}

4. Include Metadata

{
  "data": [...],
  "metadata": {
    "total": 100,
    "page": 1,
    "pageSize": 20,
    "timestamp": "2024-01-22T10:00:00Z"
  }
}

5. Handle Null Values Properly

Include null for optional fields:

{
  "name": "John",
  "middleName": null,
  "lastName": "Doe"
}

Or omit them:

{
  "name": "John",
  "lastName": "Doe"
}

Rule: Be consistent across your API!

6. Use ISO 8601 for Dates

✅ Good:

{
  "createdAt": "2024-01-22T10:30:00Z",
  "updatedAt": "2024-01-22T15:45:00+08:00"
}

❌ Avoid:

{
  "created": "01/22/2024",
  "updated": "Jan 22, 2024"
}

7. Include Type Information

{
  "items": [
    {
      "id": 1,
      "type": "product",
      "name": "Widget"
    },
    {
      "id": 2,
      "type": "service",
      "name": "Support"
    }
  ]
}

8. Use Descriptive Key Names

❌ Bad:

{
  "n": "John",
  "a": 30,
  "e": "john@example.com"
}

✅ Good:

{
  "name": "John",
  "age": 30,
  "email": "john@example.com"
}

9. Validate Your JSON

Always validate before sending:

  • Use JSON Validator
  • Implement schema validation
  • Handle parsing errors

10. Optimize for Size When Needed

Production JSON:

  • Remove whitespace with JSON Minifier
  • Use shorter key names for large datasets
  • Enable gzip compression

11. Error Handling

Standard error format:

{
  "error": {
    "code": 400,
    "message": "Bad Request",
    "details": "Missing required field: email"
  }
}

12. Versioning

Include API version:

{
  "apiVersion": "v1",
  "data": {...}
}

Security Best Practices

  1. Don't include sensitive data
  2. Validate input before processing
  3. Use HTTPS for transmission
  4. Implement rate limiting
  5. Sanitize data before output

Performance Tips

  1. Keep payloads small
  2. Use pagination for large datasets
  3. Cache responses when appropriate
  4. Compress JSON data
  5. Minimize nesting levels

Use our JSON tools to follow these best practices!