How to Format and Validate JSON
JSON is strict about syntax. Most errors come from a small set of mistakes that are quick to fix once you can see them.
The rules
- Data is an object (
{ }), an array ([ ]), a string, a number,true,falseornull. - Object keys and strings use double quotes. Single quotes are not valid.
- Items are separated by commas, with no comma after the last item.
- Comments are not allowed.
- Values such as
undefinedandNaNdo not exist in JSON. - Numbers cannot have leading zeros, such as
007.
An invalid example and its fix
This text has a single-quoted key, a trailing comma and a comment:
{
'name': "Ada",
"tags": ["a", "b",],
// comment
}Valid version:
{
"name": "Ada",
"tags": ["a", "b"]
}Format or minify?
Format JSON when people need to read it, such as in logs, documentation or debugging. Minify it when size matters, such as in network payloads. Both produce the same data.
Reading error messages
A parser reports where it gave up, which is often just after the real mistake. If an error points to a closing brace, check the line before it for a missing or extra comma. The JSON formatter shows the line and column.
Things to watch for
- Large numbers. Very large integers can lose precision in JavaScript, which stores numbers as floating-point values. Consider sending them as strings.
- Duplicate keys. The JSON format does not say how to handle them and parsers differ, so avoid them.
- Sensitive data. Be careful pasting secrets into any online tool. This one runs in your browser, but redact credentials anyway when you can.
If you pass JSON to an AI model, it also uses tokens. See How Tokenization Works.