JSON Best Practices

Updated:

JSON is the default data format for APIs, configuration, logs, and just about any data exchange between systems. Its simplicity is part of why it has won, but that same simplicity hides surprising pitfalls — silent type coercion, ambiguous numbers, inconsistent naming, and parse errors that production debuggers see far too often. This guide collects the practical rules that experienced engineers follow to keep JSON predictable and maintainable.

Always validate before you format

A pretty-printed file that is not valid JSON is still broken. Use a strict validator (like our JSON Formatter & Validator) before assuming any indentation choice fixed a problem. Common parse errors include trailing commas (not allowed in standard JSON), single quotes (only double quotes are valid), unquoted keys, and stray comments. JSON has no comment syntax — if you need to annotate, use a wrapper key like '_comment' or move to a format that supports comments (JSON5, YAML, TOML).

Choose one naming convention and stick to it

Most JSON APIs converge on lower_snake_case or camelCase for keys. Pick one for your project and apply it everywhere — mixing conventions confuses consumers and breaks code generators. snake_case is more common in Python and Ruby ecosystems; camelCase is more common in JavaScript and Java. PascalCase keys are rare and usually a sign of generated output from a strongly-typed language. Avoid kebab-case keys: JavaScript code that accesses them needs bracket notation.

Be careful with numbers

  • JSON does not distinguish between integers and floats. Many parsers will coerce based on the presence of a decimal point.
  • JavaScript can lose precision for integers larger than 2^53. If you need 64-bit IDs, serialize them as strings.
  • Avoid leading zeros (invalid JSON) and trailing decimal points (not portable).
  • Currency values should generally be sent as strings or as integer cents/minor units to avoid floating-point drift.
  • NaN and Infinity are not valid JSON. Wrap your output to convert them to null or strings before serializing.

Use arrays for ordered collections, objects for keyed lookups

An array implies order matters and consumers will iterate; an object implies keyed access where the order is irrelevant. Avoid encoding a list as an object with numeric string keys ('0', '1', '2') — this is a leak from older serializers and makes consumers reconstruct order from key sorting, which is fragile. Conversely, do not put inherently keyed data into a flat array of two-element pairs when an object would be clearer.

Handle nulls, missing keys, and empty arrays consistently

Three states have different meanings: an absent key (the field was not provided), a null value (the field was provided but has no value), and an empty array (the field was provided and contains no items). A common bug is treating all three as the same. Document which states your API can return for each field, and prefer omitting a key over sending null when the field is genuinely not applicable.

Design for evolution from day one

JSON APIs almost always need to add fields over time. Design your consumers to ignore unknown fields, and design your producers to add new optional fields rather than changing the meaning of existing ones. Reserve breaking changes for an explicit new version of the endpoint (a versioned URL or content-type).

Use JSON Schema for contracts

When two systems exchange JSON, a JSON Schema document gives both sides a machine-checkable contract. Schemas can describe required fields, types, allowed values, formats, and even cross-field validation. They are usable for documentation, client generation, and runtime validation. For internal services where you control both sides, even a lightweight schema beats no schema.

Pretty-print for humans, minify for machines

For configuration files, logs that humans will read, or anything checked into version control, pretty-print with consistent indentation (2 or 4 spaces). For network payloads where bandwidth matters, minify. Most JSON tooling can switch between the two without changing the data. Never mix — a file that is sometimes indented and sometimes minified produces diff noise.

Be defensive with untrusted input

Never use eval() to parse JSON. Use JSON.parse() (JavaScript) or your language's safe parser. Set a reasonable size limit on inbound payloads. Be aware of deep nesting attacks: most parsers happily accept JSON nested thousands of levels deep, which can be used to crash naive consumers. Reject payloads exceeding a sensible nesting depth.

常见问题

Why does my JSON file fail to parse even though it looks correct?
Common causes: trailing comma after the last element, single quotes instead of double, comments (not allowed in JSON), unquoted keys, or a UTF-8 BOM at the start of the file. Run the file through a strict validator and read the line/column reported in the error.
Should I use camelCase or snake_case in my API?
Either is fine — pick one and apply it consistently. Match the conventions of the consumers you primarily support. If your API is consumed by both JavaScript and Python clients, document the choice explicitly so neither side is surprised.
Can JSON keys be duplicated?
The standard says behavior is undefined, but parsers vary: most keep the last occurrence, some keep the first, some throw. Never rely on duplicate-key behavior. Always produce unique keys.
Is JSON5 a drop-in replacement for JSON?
No. JSON5 allows comments, trailing commas, single quotes, and unquoted keys, but standard JSON parsers will reject all of these. JSON5 is good for human-edited configuration; for interchange between systems, stick to strict JSON.

In summary

Treat JSON as a serious data format, not a free-form blob. Validate aggressively, choose conventions deliberately, and design for evolution. Our JSON Formatter & Validator catches the most common errors instantly and runs entirely in your browser — paste any JSON to verify it before shipping.

相关工具