JSON is the default format for APIs, config files, logs and data exchange. It looks
simple, which is exactly why small mistakes are so easy to make and so hard to find:
a single misplaced comma can break a 400-line document.
A JSON formatter does three jobs at once: it validates your syntax, it pretty-prints
the document so a human can read it, and it can minify it to save space. Here is how
each of those works, and a workflow you can use every time an API response or config
file misbehaves.
The three things a formatter does
Validation runs a parser over the document and either returns the parsed value or
a precise error location. A good validator tells you the line and character where
parsing failed, which is half the battle.
Pretty-printing adds indentation and puts one key-value pair on each line. The
data does not change - only whitespace does - so a pretty-printed document carries
exactly the same information in a shape your eyes can follow:
{"name":"SwiftTools","tools":50,"free":true}
becomes:
{
"name": "SwiftTools",
"tools": 50,
"free": true
}
Minifying removes all insignificant whitespace, collapsing the document to one
line - what you usually want to send over a network or store in a build artifact.
The errors that actually happen
Nearly every "my JSON is broken" case is one of these (all of them parse fine in
JavaScript, which is how they sneak in):
- Trailing comma after the last item in an array or object
- Unquoted keys ({ name: "x" } is invalid)
- Single quotes around string values
- Comments (// or /* */)
- NaN, Infinity and undefined (use null instead)
- Duplicate keys (parsers keep only the last value - data silently disappears)
A workflow for debugging API responses
- Capture the raw response from your client, a REST client, or the browser network tab. Save it exactly as received; do not edit it yet.
- Validate it. If it parses, your problem is not the syntax but the shape or values.
- Pretty-print it. With indentation, structure becomes visible at a glance.
- Search the formatted document for the field your code expects. Mismatched key names (snake_case vs camelCase) are a classic cause of "null" values.
- Minify it before pasting it into a bug report - one line beats 300.
Keep the raw copy separate from your edited version: the moment you start fixing a
suspect file by hand, you lose the evidence of what the server actually sent.
Formatting is not parsing
A document can be valid JSON and still not do what you expect. Formatting only makes
structure visible; it cannot tell you that a field has the wrong type or that a value
is off by a factor of ten. When the document validates but behaves wrongly, check the
types of the fields you rely on, and compare the payload against the documented schema.
We built SwiftTools - a free, no-sign-up collection of
50 browser-based tools. The JSON Formatter
runs entirely in your browser, so sensitive payloads never leave your machine.
Top comments (1)
tr.ee/dev-to