STRUCTURED TEXT

Compacting JSON while preserving spaces inside a string

Compacting JSON removes the layout between tokens. Spaces inside a quoted string are part of the value, so they stay, including the ones at either end.

Two kinds of space in one document

A JSON document contains whitespace in two roles. Outside strings, spaces, tabs and line breaks are layout. The grammar lets them appear before and after any structural token, and they carry no meaning. Inside a string, every space is a character of the value. In the example { "label" : " red blue " } the spaces around the colon and the braces are layout, while the string contains a leading space, the word red, two spaces, the word blue and a trailing space. That makes ten characters between the quotes. A compacting step may delete the first kind and must never touch the second, because deleting it would change what the document says.

What compaction does to the example

With the indent control set to 0, the formatter parses the document and writes it out with no optional whitespace. The input { "label" : " red blue " } becomes {"label":" red blue "}. The braces and colon now touch their neighbors, and the string token is byte for byte what it was. The result reports valid as true. Count the characters inside the quotes before and after: ten in both. This is the expected behavior for any correct minifier, and it is also why a minified file can be smaller than its readable version by a large factor on deeply indented data but never smaller in the string contents.

Pretty-printing the same value

The second case runs the compact form back through the formatter with an indent of 2 and returns three lines: an opening brace, the label member indented by two spaces with a single space after the colon, and a closing brace. The newline characters and the indentation are new layout, and the string " red blue " still has its leading space, double space and trailing space. Pretty-printing and compacting are inverse layout operations on the same data, so they can be applied in either order without changing the parsed result. Only the spacing outside strings differs between the compact and indented outputs. If you choose an indent of 4 instead of 2, the member moves four spaces from the margin, and the quoted text inside the string stays the same. That makes the indent setting a matter of reading preference, to be chosen to match a project style guide, and never a way to change data.

Trimming is a separate operation

People sometimes expect compaction to clean up values, and then conclude something went wrong when a trailing space survives. Trimming text is a content change. Whether it is appropriate depends on the field: a postal code with a trailing space probably should be trimmed before it is stored, while a fixed-width record or a padded token may rely on its spaces. Because the JSON formatter cannot know which case applies, it leaves string content to you. If a receiving system rejects a value for leading or trailing spaces, fix the value at its source or in a dedicated normalization step, then format the document afterward.

Spotting invisible spaces in a string

Spaces at the end of a value are invisible in most editors, so the quotes are the best guide. In the compact output the closing quote sits one character after the word blue, and the opening quote sits one character before the word red. Those gaps tell you the string begins and ends with a space. Tabs and other whitespace characters inside a string must be written as escapes in JSON: a literal tab inside quotes is not valid, and the parser will flag it, whereas a plain space is allowed. Non-breaking spaces, U+00A0, are not whitespace to the JSON grammar at all, and one outside a string makes the document invalid.

Which characters count as layout

The JSON grammar defines whitespace as exactly four characters: space, horizontal tab, line feed and carriage return. A byte order mark, a form feed or a Unicode space such as U+2003 is not layout, and a strict parser rejects them outside a string. That narrow definition is what lets minifiers be simple and safe. It also explains a common surprise when text is pasted from a word processor or chat window, where invisible characters sneak in between tokens. The error the formatter shows in that situation points at a syntax problem, and the fix is to remove the stray character, not to expect compaction to absorb it.

Where compaction pays off

Compact JSON suits network payloads, query strings, environment variables and log lines, where every byte or line counts and nobody reads the layout. Readable JSON suits configuration files, code review and debugging. Moving between them is routine, and the check in this example confirms that nothing in the data changes in the move. Compaction does not compress the data in any other way: keys, string content and number spelling remain as written. For large files, transfer compression such as gzip removes far more size than whitespace removal does, so the two techniques are often used together. In the example here the readable form with an indent of 2 takes three lines, and the compact form takes one, a difference of a few characters that matters only when thousands of such records are stored or sent.

Whitespace around numbers, keys and nesting

The same split applies to the rest of a document. Spaces between a key and its colon, after a comma or before a closing bracket are layout and disappear in compact output. Keys are strings too, so a key such as " id" with a leading space is a different key from "id" and is preserved exactly. Arrays and nested objects behave alike: the formatter reflows their layout and leaves every string token alone. Numbers contain no layout, since a space inside a number makes the document invalid. When a downstream system complains about a missing property, look for a key with an invisible space in it before suspecting the formatter or the data source.

Checking the result in your own data

To test your own document, paste it, set the indent to 0 and look at the formatted output. Search the original for runs of spaces inside quotes and confirm that each run appears again in the compact version. Then switch the indent to 2 and confirm the same runs once more. If a space inside a string seems to vanish, the likely cause is a display that collapses repeated spaces, as HTML does, rather than the formatter. Copying the output into a plain text editor with a monospaced font settles the question quickly.

Reproduce the checks

Compact the document

Open the Json Validator Formatter and enter:

JSON input
{ "label" : " red  blue " }
Indent
0

Expected output:

Valid

true

Formatted

{"label":" red  blue "}

Only whitespace outside the string token is removed.

Pretty-print the same value

Open the Json Validator Formatter and enter:

JSON input
{"label":" red  blue "}
Indent
2

Expected output:

Valid

true

Formatted

{
  "label": " red  blue "
}

Added layout does not alter the internal spaces.

References and implementation scope

The examples describe the behavior of the linked Computandum tools. A successful local check does not establish that another application accepts the same format or applies the same limits.

Sources

Related tasks