How to format and validate JSON
JSON is the format most web APIs and settings files use, and it is strict: one stray comma and the whole document is rejected. Formatting makes JSON readable, and validating tells you whether it is correct and where it is not.
Try it now: JSON Formatter & Validator, JSON Diff, YAML to JSON & JSON to YAML.
What formatting and validating mean
Formatting, also called pretty-printing, adds line breaks and indentation so the structure is easy to read. It does not change the data. The opposite, minifying, removes all the extra whitespace so the text is as small as possible, which is useful just before you send it over a network.
Validating checks that the text follows the JSON rules. A valid document has a single value at the top, usually an object or an array, with every bracket closed and every string in double quotes. A good validator reports the line and column of the first problem, so you do not have to hunt for it.
The mistakes that break JSON
Most invalid JSON comes from a short list of habits carried over from JavaScript or from hand editing.
| Mistake | Example | Fix |
|---|---|---|
| Trailing comma | {"a": 1,} | Remove the last comma |
| Single quotes | {'a': 1} | Use double quotes |
| Unquoted key | {a: 1} | Write "a" in double quotes |
| Comment | {"a": 1} // note | JSON has no comments; delete it |
| Missing comma | {"a": 1 "b": 2} | Add a comma between the pairs |
| Undefined or NaN | {"a": undefined} | Use null, or leave the key out |
| Unclosed bracket | {"a": [1, 2} | Close the array before the object |
How to format JSON and find an error
Paste your text into the JSON formatter and choose an indent. If the text is valid, you get the readable version straight away. If it is not, the message names the line and column, for example an unexpected character after the last property. Fix that spot and run it again, because the first error can hide the next one.
Here is a small document that fails, and the same document fixed:
{"name": "Ada", "tags": ["math", "code",], "active": true,}
{
"name": "Ada",
"tags": ["math", "code"],
"active": true
}Valid is not the same as correct
A validator only checks the syntax. A document can be valid JSON and still be wrong for your use, for example a date in the wrong format or a number where a string is expected. Checking the shape of the data is a separate job, done with a schema or with your own code.
Comparing two JSON documents
When two versions of a response or a settings file differ, reading them side by side is slow and easy to get wrong, especially when the keys are in a different order. A JSON comparer ignores key order and lists every value that was added, removed or changed, with its path, so you see exactly what moved.
JSON and YAML
Configuration files are often written in YAML, which is easier to read and allows comments. YAML can be turned into JSON and back, but comments are lost on the way to JSON, because JSON cannot hold them.