All articles
Formatters
7 min readBy DevUtilX Team

JSON Formatting Guide: Beautify, Validate and Minify

Learn how JSON works, the mistakes that break parsers, and when to beautify, validate or minify your data, with practical examples.

JSON Formatting Guide: Beautify, Validate and Minify

JSON is the default language of web APIs, configuration files and data exchange. It is also unforgiving: a single stray comma can break a deployment. This guide explains what JSON actually is, why formatting matters, which mistakes break parsers most often, and when to beautify, validate or minify your data.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based format for representing structured data. It was derived from the object literal syntax of JavaScript, but it is language independent, and nearly every programming language ships with a parser for it. The format is described in RFC 8259, which is also Internet Standard STD 90, and in the short description on json.org. The Wikipedia article on JSON gives a good history of how it became the dominant data interchange format.

A JSON document is built from just two structures and a handful of value types:

  • Objects: unordered collections of key/value pairs wrapped in curly braces, such as {"name": "Ada"}.
  • Arrays: ordered lists of values wrapped in square brackets, such as [1, 2, 3].
  • Values: a string, a number, true, false, null, or another object or array.

That small surface area is the reason JSON won. It is easy for people to read and trivial for machines to parse.

Why JSON formatting matters

JSON itself does not care about whitespace. The parser treats the following two documents as identical:

{"user":{"id":42,"name":"Ada","roles":["admin","editor"]}}
{
  "user": {
    "id": 42,
    "name": "Ada",
    "roles": [
      "admin",
      "editor"
    ]
  }
}

Humans care a great deal, though. Formatting affects three things in practice.

Readability. Nested structures are nearly impossible to scan on one line. Indentation shows hierarchy at a glance, so you can see which keys belong to which object.

Debugging. When an API returns a 200 KB response and one field has the wrong value, you need to find that field quickly. Pretty-printed output lets you search, fold and compare sections.

Version control. A minified file changes entirely on every edit, so the diff is one enormous line. A consistently formatted file with one key per line produces small, reviewable diffs.

Consistency matters as much as the style you pick. Two spaces is the most common indent in JavaScript projects, four spaces is common elsewhere, and tabs work too. Choose one for the project and let a tool enforce it.

Beautifying JSON

To beautify (or pretty-print) JSON means to re-serialize it with line breaks and indentation. You can do this without leaving the language you are working in. In JavaScript, the built-in JSON object, documented on MDN, takes an indent argument:

const raw = '{"user":{"id":42,"name":"Ada"}}';
const pretty = JSON.stringify(JSON.parse(raw), null, 2);
console.log(pretty);

The third argument controls the indent. A number sets that many spaces (up to ten), and a string such as "\t" uses that string instead. The second argument is a replacer, which can be a function or an array of keys to keep. You can use it to drop sensitive fields before logging:

JSON.stringify(user, ['id', 'name'], 2);

Python offers the same thing with json.dumps(data, indent=2), and on the command line python -m json.tool or jq . will reformat a file.

For quick one-off jobs, an online tool is faster. The JSON Beautifier lets you paste a payload, choose an indent, and copy the result. It runs in your browser, so the data you paste is not uploaded anywhere.

Use beautified JSON when:

  • you are reading or debugging a response by eye,
  • the file is committed to a repository,
  • the file is a configuration file that people edit by hand,
  • you are writing documentation or examples.

Validating JSON

Beautifying only works if the input is valid. Validation answers a different question: is this text legal JSON at all? The grammar is strict, and a parser will reject anything outside it. If your tooling gives you a vague error such as Unexpected token } in JSON at position 87, a validator that points to the exact line and column saves a lot of time.

The JSON Validator checks the syntax and reports where it fails. Validate whenever the data comes from somewhere you do not control: user uploads, third-party APIs, copied snippets, or files edited by hand.

Syntax validation has limits, however. It confirms that the document is well formed, not that it contains the right data. A payload with "age": "forty" is perfectly valid JSON even if your application expects a number. For that, you need schema validation, covered below.

The mistakes that break parsers

Most invalid JSON comes from a short list of habits, many of them imported from JavaScript, where the syntax is more relaxed. The DEV Community article on 25 common JSON mistakes covers many more, but these are the ones that show up most often.

Trailing commas. JavaScript permits a comma after the last item. JSON does not.

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

The comma after "admin" makes this invalid. Remove it.

Single quotes. Strings and keys must use double quotes. {'name': 'Ada'} is valid JavaScript and invalid JSON.

Unquoted keys. {name: "Ada"} works as a JavaScript object literal. In JSON every key must be a double-quoted string.

Comments. JSON has no comment syntax. Neither // note nor /* note */ is allowed. If you need comments in a configuration file, consider a superset such as JSON5 or a different format like YAML, or add a conventional key such as "_comment" and accept that it becomes data.

Invalid values. undefined, NaN and Infinity are not JSON values. The only literals are true, false and null. Note that JSON.stringify silently turns NaN and Infinity into null, and omits keys whose value is undefined, which can surprise you.

Leading zeros and bad numbers. 007, +5, .5 and 0xFF are all invalid. Write 7, 5, 0.5 and 255.

Unescaped characters in strings. A raw newline or tab inside a string breaks parsing. Use \n and \t, and escape quotes and backslashes: "She said \"hi\"" and "C:\\temp".

Duplicate keys. The RFC says names within an object SHOULD be unique, and behavior with duplicates is unpredictable. Some parsers keep the first, some keep the last, and some throw.

Wrong character encoding. RFC 8259 requires JSON exchanged between systems to be encoded as UTF-8. A byte order mark at the start of the file also trips up some parsers.

Large integers. JSON itself places no limit on number size, but JavaScript represents numbers as 64-bit floats. Integers above 2^53 − 1 lose precision when parsed. Twitter-style 64-bit IDs are the classic example, and the usual fix is to transmit them as strings.

A good habit is to run suspicious data through a validator before you spend time debugging your own code. Nine times out of ten the problem is one of the items above.

Minifying JSON

Minification is the opposite of beautifying. It removes every character that is not needed: spaces, tabs and line breaks outside of strings. The data stays exactly the same. Only its size changes.

const minified = JSON.stringify(JSON.parse(pretty));

Calling JSON.stringify without an indent argument produces compact output. The JSON Minifier does the same in the browser and shows how many bytes you saved.

Why minify?

  • Smaller payloads. Whitespace in a deeply nested document can add 20 to 40 percent to its size. That is bandwidth you pay for and latency your users feel.
  • Faster parsing and transfer on slow mobile connections.
  • Lower storage costs when you keep millions of documents.

Be realistic about the gain, though. If your server already compresses responses with gzip or Brotli, which it should, the difference between pretty and minified JSON shrinks a lot, because repeated whitespace compresses very well. Minification still helps, but it is not a replacement for compression. And never minify files that humans maintain: you will save a few bytes and lose all readability.

A practical rule: beautify for people, minify for machines. Keep source files and logs readable, and ship compact JSON over the wire.

Going beyond syntax: JSON Schema

When you need to guarantee not just valid syntax but valid structure, use JSON Schema. A schema is itself a JSON document that describes what your data must look like: which properties exist, which are required, what type each one has, and what ranges or patterns are allowed. The official Understanding JSON Schema guide is the best place to learn it.

{
  "type": "object",
  "required": ["id", "name"],
  "properties": {
    "id": { "type": "integer", "minimum": 1 },
    "name": { "type": "string", "minLength": 1 },
    "roles": {
      "type": "array",
      "items": { "type": "string" }
    }
  }
}

With a library such as Ajv in JavaScript or jsonschema in Python, you can reject bad input at the edge of your application and produce clear error messages, instead of discovering the problem three layers deeper in a stack trace.

A sensible JSON workflow

Putting the three operations together, a workflow that holds up in real projects looks like this:

  1. Validate first. Confirm the text is well-formed JSON. Fix syntax errors at the source.
  2. Beautify to inspect. Format the data with a consistent indent so you can read and review it.
  3. Check the structure. If the data feeds an application, validate it against a schema.
  4. Minify to ship. Compact the data for transport or storage, and let your server compress it as well.
  5. Automate it. Add a formatter to your editor or a pre-commit hook so nobody formats by hand, and run validation in CI so broken JSON never reaches production.

Security and privacy considerations

Data you paste into an online formatter may be sensitive: API responses with tokens, customer records, internal configuration. Prefer tools that process everything locally in your browser, and check that they say so. Do not paste secrets into services that upload your input to a server.

When you parse JSON in your own code, treat it as untrusted input. Use JSON.parse rather than eval, which will execute arbitrary code. Set size limits on request bodies, and be careful with deeply nested documents, which can exhaust the stack in some parsers.

Quick reference

Task Goal Typical tool
Beautify Make it readable JSON.stringify(obj, null, 2), JSON Beautifier
Validate Find syntax errors JSON.parse in try/catch, JSON Validator
Minify Make it small JSON.stringify(obj), JSON Minifier
Schema check Verify structure JSON Schema with Ajv or jsonschema

Conclusion

JSON succeeds because it is simple, but simple does not mean forgiving. Knowing the handful of rules that parsers enforce (double quotes, no trailing commas, no comments, limited value types) will prevent most errors before they happen. Beautify when people need to read the data, validate whenever you do not trust where it came from, and minify when bytes matter. Add a schema when structure matters as much as syntax.

If you have a payload open right now, try the JSON Validator on it, then format it with the JSON Beautifier. Both run in your browser, so your data stays on your machine.

Try the tools

Further reading

Related articles