🍋
Menu
Best Practice Beginner 1 min read 268 words

JSON Formatting and Validation: Best Practices for Clean Data

Best practices for formatting, validating, and structuring JSON data. Covers indentation standards, JSON Schema validation, common syntax errors, and the differences between JSON and JSON5.

Key Takeaways

  • JSON has a single universal syntax — no competing standards or flavors.
  • Trailing comma**: `{"a": 1,}` — invalid in JSON (valid in JS/JSON5)
  • JSON Schema defines the expected structure, types, and constraints of your JSON data.
  • JSON5 relaxes JSON's strict syntax — allowing comments, trailing commas, single quotes, and unquoted keys.
  • For data interchange, always use standard JSON.

JSON Formatting Standards

JSON has a single universal syntax — no competing standards or flavors. Yet formatting varies widely: minified for production, pretty-printed for debugging, and sorted keys for deterministic output. Consistent formatting prevents unnecessary diff noise in version control.

Formatting Conventions

Convention When Benefit
2-space indent Most codebases Compact, readable
4-space indent Python ecosystems Extra readability
Sorted keys Config files, snapshots Deterministic diffs
Minified API responses, storage Minimal size
One item per line Arrays of objects Clean diffs

Common Syntax Errors

  • Trailing comma: {"a": 1,} — invalid in JSON (valid in JS/JSON5)
  • Single quotes: {'a': 1} — invalid, must use double quotes
  • Unquoted keys: {a: 1} — invalid, keys must be quoted strings
  • Comments: // comment — not allowed in JSON
  • Infinity/NaN: Not valid JSON values

JSON Schema Validation

JSON Schema defines the expected structure, types, and constraints of your JSON data. It catches type errors (string where number expected), missing required fields, and invalid enum values before they cause runtime failures. Use schemas for API request/response validation and configuration file validation.

JSON5 and Alternatives

JSON5 relaxes JSON's strict syntax — allowing comments, trailing commas, single quotes, and unquoted keys. It is popular for configuration files that humans edit directly. For data interchange, always use standard JSON.

Format, validate, and transform JSON with the Peasy JSON tools — supports pretty-printing, minification, sorting, and JSON Schema validation.