All articles
Formatters
22 min readBy Akash Bijwe

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.

How a JSON parser reads your text

Understanding what happens inside a parser makes error messages far less mysterious. A parser works in two stages. First a tokenizer (or lexer) walks the characters and groups them into tokens: punctuation such as {, }, [, ], : and ,, plus strings, numbers and the three literals. Then the parser checks that the tokens arrive in a legal order, for example that a colon follows every key and that a comma separates, but never trails, the members of an object.

Whitespace is only legal in four forms: space, horizontal tab, line feed and carriage return. Anything else, including a non-breaking space pasted from a web page or a word processor, is an illegal character. This is a surprisingly common cause of "invalid JSON" that looks perfectly fine on screen.

Because the grammar is so small, parsers can be fast and can reject bad input at the first offending character. That is why the reported position is usually the place where the parser noticed the problem, which can be a little after the place where you made it. A missing comma between two members is only detected when the next key appears. A missing closing quote is only detected when something illegal shows up later in what the parser believes is still a string.

Modern engines also include line and column in the message. Running a few broken inputs through Node.js shows the style:

try { JSON.parse('{"a":1,}'); } catch (e) { console.log(e.message); }
// Expected double-quoted property name in JSON at position 7 (line 1 column 8)

try { JSON.parse("{'a':1}"); } catch (e) { console.log(e.message); }
// Expected property name or '}' in JSON at position 1 (line 1 column 2)

Exact wording differs between engines and versions, so never write code that matches on the message text. Catch the exception and treat any failure as "invalid input".

A short history and the design rationale

JSON was popularized in the early 2000s as a way for browsers and servers to exchange data without the weight of XML. Its author has said he discovered the format rather than invented it, because the syntax already existed inside JavaScript. The early habit of passing such text to eval was convenient and dangerous, which is why a dedicated parser, and later the built-in JSON object, became standard.

Several design choices explain behavior that surprises newcomers:

  • No comments. The format was meant purely for data interchange between programs. Comments invite people to stash directives in them, which would break interoperability between parsers.
  • No trailing commas, no single quotes, no unquoted keys. Each strict rule removes an ambiguity, so one rule set works in every language.
  • Only one number type. JSON says that numbers are written in decimal and says nothing about binary precision. Each implementation decides how to store them, which is why large integers and decimals behave differently across languages.
  • Unordered objects. The specification describes an object as an unordered collection. Many libraries preserve insertion order, but you should not depend on it when exchanging data with other systems.

These constraints are exactly why a one-line formatter can be trusted: the data model is so small that formatting never needs to guess.

Indentation, ordering and style conventions

The formatter you pick decides more than the indent width. Settle these questions once and write the answers down.

Indent width. Two spaces is compact and works well for deeply nested documents. Four spaces is easier to scan for shallow structures. Tabs let each reader choose their own visual width, which helps accessibility for people who prefer wider or narrower indents.

Key order. JavaScript's JSON.stringify writes keys in a specific order: integer-like keys first in ascending numeric order, then other string keys in insertion order. You can see the effect directly:

JSON.stringify({ b: 1, 2: 1, a: 1, 1: 1 });
// {"1":1,"2":1,"b":1,"a":1}

If you want stable diffs, sort keys when you write the file. Python does it with json.dumps(data, sort_keys=True, indent=2), and jq -S . does it on the command line. Sorted keys are ideal for generated files such as lockfiles and snapshots. For hand-edited configuration, keep a meaningful human order (name first, then settings by topic) and do not sort.

Short arrays. Standard formatters put every array element on its own line, so an array of ten numbers takes twelve lines. Some tools keep short arrays inline. Either is fine, as long as the whole team uses the same tool.

Empty containers. {} and [] stay on one line in JSON.stringify output, even when the surrounding structure is expanded:

JSON.stringify({ a: [1, 2], b: {}, c: [] }, null, 2);

Trailing newline. End files with a single newline. Many editors and git diff flag a missing one with "no newline at end of file", which adds noise to otherwise clean diffs.

Non-ASCII text. Python's json.dumps escapes non-ASCII characters by default, so "é" becomes "é". Pass ensure_ascii=False to keep readable text, as long as you write the file as UTF-8. JavaScript's JSON.stringify leaves non-ASCII characters alone.

What JSON.stringify does to values it cannot represent

Round-tripping data through JSON.stringify and JSON.parse is lossy for several types. Knowing the rules prevents silent data loss:

JSON.stringify({
  d: new Date(0),
  u: undefined,
  f() {},
  n: NaN,
  a: [undefined, () => 1],
});
// {"d":"1970-01-01T00:00:00.000Z","n":null,"a":[null,null]}

The pattern is consistent:

  • Dates become ISO 8601 strings through their toJSON method, and they come back as plain strings. JSON.parse never restores a Date.
  • Properties holding undefined, functions or symbols are omitted from objects.
  • The same values inside arrays become null, to preserve positions.
  • NaN and Infinity become null.
  • A BigInt throws a TypeError ("Do not know how to serialize a BigInt").
  • Circular references throw a TypeError ("Converting circular structure to JSON").
  • Map and Set serialize as {} because they have no enumerable own properties.

You can customize any of this with a toJSON method or a replacer function. For example, to serialize big integers as strings and sets as arrays:

function replacer(key, value) {
  if (typeof value === 'bigint') return value.toString();
  if (value instanceof Set) return [...value];
  return value;
}

JSON.stringify({ id: 9007199254740993n, tags: new Set(['a', 'b']) }, replacer, 2);

The mirror image is the reviver, the optional second argument of JSON.parse. It receives every key and value, from the innermost values outward, and returns the value to keep:

JSON.parse('[1,2]', (key, value) => (typeof value === 'number' ? value * 2 : value));
// [2, 4]

Use revivers to turn date strings back into Date objects, but be explicit about which keys you convert. Converting every string that looks like a date will eventually corrupt a field that merely resembles one.

Numbers, precision and money

Because JavaScript parses every JSON number into a 64-bit float, integers beyond 2^53 − 1 are rounded:

JSON.parse('9007199254740993');
// 9007199254740992

The value in the document was exact. The loss happened in the parser. Python, Java and Go can read the same text into exact integers or decimals, so the problem only appears when a JavaScript consumer touches the data. Three defenses work well:

  1. Send identifiers as strings. Opaque IDs do not need arithmetic, so a string loses nothing.
  2. Send money as integer minor units (for example, cents) or as decimal strings, never as binary floats. 0.1 + 0.2 is not 0.3 in floating point, and rounding errors accumulate.
  3. Document the range. If a field is guaranteed to fit in 32 bits, say so in the schema with minimum and maximum.

Formatters that parse and re-serialize your document inherit the same limitation. If a formatter must preserve exact digits, choose one that works on the token stream and never converts numbers, or check what it does with a very large literal before you trust it on production data.

Troubleshooting guide: symptom, cause, fix

When a parse fails, work from the symptom. This table covers the cases that account for most support questions.

Symptom Likely cause Fix
Error at the very first character The response is HTML (an error page or login redirect), or the file starts with a byte order mark Print the first 200 characters of the raw body; strip the BOM; check the status code and Content-Type before parsing
Unexpected end of JSON input Empty body, truncated download, or a stream cut short Check Content-Length, handle 204 responses without parsing, and retry on network errors
Error right after a value Missing comma between members Add the comma; formatters usually point at the next key
Error at a closing brace or bracket Trailing comma before it Remove the last comma
Error inside a string Raw newline, tab or unescaped quote Escape with \n, \t and \", or build the data with a serializer instead of by hand
Unexpected token ' or a quote complaint Single-quoted keys or strings Replace with double quotes
Works in the console, fails in the parser Input is a JavaScript object literal, not JSON Quote the keys and remove comments, functions and undefined
Unexpected non-whitespace character after JSON Two documents concatenated, or logs written one per line Parse each line separately (JSON Lines) or fix the writer
Numbers look slightly wrong Precision loss above 2^53 − 1 Use strings for IDs and exact decimals
Accented characters appear as garbage File saved in a legacy encoding Re-save as UTF-8 and set the charset on the response
Invisible failure with perfect-looking text Non-breaking space or smart quotes pasted from a document Retype the characters, or run the text through a validator that reports the offending column

A reliable debugging routine takes under a minute. First, print the raw text exactly as the parser received it, with JSON.stringify(text) so invisible characters show up as escapes. Second, validate it. Third, bisect: delete half the document and see whether the error moves.

Walkthrough: fixing a broken configuration file

Suppose a teammate hands you this settings file and the application refuses to start:

{
  // build settings
  name: 'web-app',
  "port": 08080,
  "features": ["search", "export",],
  "debug": True
}

Run it through the JSON Validator and fix errors one at a time, because a parser stops at the first problem. The sequence goes like this.

  1. The comment on line 2 is the first illegal token. Delete it. If the comment carries information, move it into documentation or a "description" field.
  2. name needs double quotes, and so does its value: "name": "web-app".
  3. 08080 has a leading zero. Write 8080.
  4. The trailing comma inside the features array has to go.
  5. True is Python or YAML spelling. JSON booleans are lowercase: true.

The corrected file:

{
  "name": "web-app",
  "port": 8080,
  "features": ["search", "export"],
  "debug": true
}

Notice how many of those errors came from habits borrowed from other languages. That is a hint for prevention: edit configuration in an editor with JSON language support, so each mistake is underlined as you type, rather than discovering all five at deploy time.

Working with large files and streams

A formatter that calls JSON.parse loads the entire document into memory as objects, and the in-memory representation is usually several times larger than the text. A file that is comfortable at a few megabytes can become painful at hundreds. Keep these points in mind.

Browser tools run on the main thread unless they use a worker, so a very large paste can freeze the tab for a moment. If it happens, trim the document to the relevant part before pretty-printing.

Command-line tools handle big files better. jq can stream with --stream, and it can extract a small piece without printing the whole file:

jq '.items[] | select(.status == "failed") | .id' export.json

Line-delimited JSON (often called JSON Lines or NDJSON) stores one compact document per line. It suits logs and exports because a reader can process one record at a time and a crash loses at most one line. Each line must be minified, since a line break ends the record, so this is a case where compact output is required rather than merely efficient.

Streaming parsers exist in most languages and emit events instead of building a tree. Reach for one when you need to process data that does not fit in memory, and when you only need a few fields from a huge document.

Pretty-printing also increases size, as the next section explains, so avoid sending indented JSON between services that handle large volumes.

Performance and payload size, measured

Claims about size savings are easy to verify on your own data. This Node.js snippet compares a document before and after compression, so you can see the effect for yourself:

const zlib = require('zlib');

const data = require('./sample.json');
const pretty = JSON.stringify(data, null, 2);
const compact = JSON.stringify(data);

const size = (s) => Buffer.byteLength(s);
const gz = (s) => zlib.gzipSync(s).length;

console.log('pretty', size(pretty), 'gzip', gz(pretty));
console.log('compact', size(compact), 'gzip', gz(compact));

Run it against a real response from your API. Typically the raw difference is substantial and the gzip difference is small, because compression removes the repeated runs of spaces. The raw size still matters in places that do not compress: memory use, log storage that counts raw bytes, and clients that parse the text.

The bigger wins usually come from the data itself, not the whitespace: removing fields nobody reads, avoiding repeated long key names in large arrays, paginating, and using a replacer to omit internal properties. For a deeper treatment of these trade-offs, see JSON minification and payload size.

Formatting in your editor

Do not format by hand when your editor can do it on save. Setup takes a few minutes and pays off permanently.

Visual Studio Code has built-in JSON support. The command Format Document re-indents the file, and the editor validates syntax as you type. Files such as tsconfig.json and settings.json use the "JSON with Comments" mode, which allows comments, so the squiggles you see there follow different rules from strict JSON. Enable format on save in your settings and set the indent through the editor's tab size setting.

JetBrains IDEs include a JSON formatter and an optional inspection that flags comments and trailing commas in strict files.

Vim and Neovim users can pipe the buffer through a formatter: :%!jq . re-indents the whole file in place, and :%!jq -S . also sorts keys.

Prettier is the most common cross-editor choice in JavaScript projects. It formats .json files with the same rules everywhere, which keeps diffs consistent across a team. It also supports .json5 and .jsonc files when you need comments.

Whatever you choose, commit a shared configuration (an .editorconfig file is the simplest) so every contributor's editor produces identical output.

Enforcing format in pre-commit hooks and CI

Editor settings are a convenience; automation is the guarantee. Two layers cover almost every team.

A pre-commit hook formats or checks staged files before they enter history. With a Node-based project, tools such as lint-staged run a command only on the files you changed:

{
  "lint-staged": {
    "*.json": "prettier --write"
  }
}

A CI check catches anything that slipped through, including commits made on machines without the hook. Run the formatter in check mode, which fails when a file would change, rather than in write mode:

npx prettier --check "**/*.json"

For a dependency-free syntax check, jq returns a non-zero exit status on invalid input, so a loop is enough:

for f in $(git ls-files '*.json'); do
  jq empty "$f" || exit 1
done

If your repository includes strict-JSON files that tools read as data, exclude intentionally commented files such as editor settings from the strict check, or you will chase false failures.

Add schema validation as a third layer for files with a defined structure, such as feature flags or localization bundles. A failing schema check in CI is much cheaper than a failing deploy.

Comparing and reviewing JSON changes

Formatting is what makes review possible. When two versions of a file use the same indent and key order, a text diff shows exactly the keys that changed. When they do not, every line differs. Before comparing two payloads that came from different sources, beautify both with identical settings and sort their keys, then diff the results. Our guide to code diff and comparing files explains how to read the output effectively.

For API responses, remember that array order usually carries meaning while object key order does not. A good comparison treats a reordered array as a change and a reordered object as no change at all.

JSON is not always the best fit, and its neighbors solve specific problems.

  • JSON5 and JSONC allow comments, trailing commas and unquoted keys. They are pleasant for hand-written configuration, but a strict parser will reject them, so convert before sending to a service that expects plain JSON.
  • YAML supports comments and is common in infrastructure tooling. Its indentation-sensitive syntax creates a different class of mistakes. YAML 1.2 was designed so that most JSON documents are also valid YAML, but do not rely on that overlap in tooling.
  • XML has attributes, namespaces and mixed content that JSON lacks. If you work with it, see XML formatting and structure.
  • GraphQL responses are JSON, so everything in this guide applies to them. For the query side, see GraphQL query formatting.
  • Binary formats such as MessagePack or Protocol Buffers are smaller and faster to parse but cannot be read by eye. Choose them when throughput matters more than debuggability, and keep a JSON view available for troubleshooting.

JavaScript developers who want to keep the surrounding code as tidy as the data can read our guide to JavaScript code formatting best practices.

A team checklist for JSON files

Copy this list into your contributing guide and adjust it to your project.

  • Every .json file is valid, strict JSON unless its name or tooling says otherwise.
  • One indent style, enforced by a formatter, never by reviewers.
  • Files end with a single newline and use UTF-8 without a byte order mark.
  • Generated files have sorted keys; hand-edited files keep a documented order.
  • Identifiers and money are strings or integers, never floats.
  • Schemas live next to the data they describe and run in CI.
  • Secrets never appear in committed JSON. Use environment variables or a secrets manager.
  • Logs use one compact document per line; documentation examples are pretty-printed.
  • Public APIs are compressed by the server, and the team has measured payload size at least once.

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

Frequently asked questions

Can JSON have comments?

Not in the standard. Strict parsers reject // and /* */. Use JSONC or JSON5 for hand-edited files, YAML if your toolchain supports it, or keep the explanation in a separate README. A "_comment" key works but travels with the data, so consumers will see it.

Is the order of keys in an object guaranteed?

The specification treats objects as unordered, so another system may reorder them. JavaScript engines do preserve a defined order (integer-like keys first, then insertion order), and Python dictionaries keep insertion order. Rely on order only inside a single program. Use an array when order is part of the meaning.

What is the difference between JSON.parse and eval?

JSON.parse accepts only the JSON grammar and cannot run code. eval runs any JavaScript it receives, so a malicious payload can do anything your page can do. Never use eval on data.

Why does my formatter change my numbers?

Some tools parse numbers into floating point and print them back. 1.0 can become 1, 1e3 can become 1000, and very long integers can lose digits. If exact text matters, use a formatter that preserves number tokens, or store the value as a string.

Does pretty-printing change the data?

No. Whitespace outside strings is not data. A correct formatter produces a document that parses to exactly the same value. Whitespace inside strings is data and must never be touched.

Should I minify JSON in my repository?

Rarely. Commit readable, formatted files and let your build step minify what gets shipped. Minified source files make diffs and reviews close to useless.

How do I handle a UTF-8 byte order mark?

JSON exchanged between systems should not carry one, and RFC 8259 says parsers may ignore it. Many do not. Save files as "UTF-8" rather than "UTF-8 with BOM", or strip a leading \uFEFF character before parsing.

Can I put several JSON documents in one file?

Not as plain JSON: after the first value the parser expects the end of input. Wrap the documents in an array, or use one compact document per line (JSON Lines) and parse line by line.

How deep can JSON be nested?

The grammar sets no limit, but real parsers do, and recursive parsers can run out of stack on extreme depth. Set a depth or size limit on untrusted input, and keep your own documents shallow enough to read.

Is it safe to paste production data into an online formatter?

Only if you know the tool works locally. The tools on this site run in your browser, but as a rule, strip tokens, passwords and personal data from anything you share, wherever you paste it.

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.

Further reading

Try the tools

Further reading

Related articles