JSON Formatting and Validation: What Actually Trips People Up

By · Published

Most “JSON is broken” bug reports come down to one of three things, and it's almost never the tool that's wrong.

Trailing commas

JavaScript object literals allow this and JSON does not:

{
  "name": "Ada",
  "role": "engineer",
}

The comma after "engineer" is valid in a JS file and invalid in a JSON file. Copy an object literal out of your editor, paste it into a JSON validator, and this is usually the first error you hit.

Single quotes and unquoted keys

{ name: 'Ada' } is convenient JS shorthand. JSON requires double quotes on both keys and string values, no exceptions:

Advertisement
{ "name": "Ada" }

NaN, undefined, and Infinity aren't valid values

Run JSON.stringify({ x: NaN }) in a browser console and you get back {"x":null}. JavaScript converts it without telling you. But if something upstream writes NaN or undefined straight into a JSON string (some Python serializers do this by default with allow_nan=True), the result is technically invalid JSON. A strict parser will reject it, even though it looks harmless.

What “pretty-print” does

Pretty-printing re-serializes the parsed structure with indentation. The data stays the same, with one exception. The spec technically allows duplicate keys, and parsers disagree on how to handle them (most keep the last one). Pretty-printing will silently drop the earlier duplicate, because by the time it formats anything it's working from the parsed object, not the raw text. Catching duplicate keys is a separate check from formatting.

Sorting keys before you diff

If you're about to compare two JSON blobs by eye, sort the keys first. Two identical objects with keys in a different order look different at a glance, and you'll waste time chasing a difference that isn't there. For a structural diff, use a JSON diff tool instead of eyeballing formatted output.

Advertisement

Try the JSON Formatter →

Related tools & guides

Part of JSON Tools: Format, Validate, Diff, Convert, and Generate Types