How do I remove whitespace from JSON?

Dark navy cover card with the title 'How do I remove whitespace from JSON?' in white and a green accent bar

To remove whitespace from JSON, parse it and serialize it again without indentation. In JavaScript that is JSON.stringify(JSON.parse(text)), in Python it is json.dumps(data, separators=(',', ':')), and on the command line it is jq -c .. Don't delete spaces with find-and-replace, because that also removes the spaces inside your string values.

Which whitespace in JSON is safe to remove?

You can remove any whitespace that sits between JSON tokens, and nothing else. The JSON standard says "insignificant whitespace is allowed before or after any of the six structural characters". Those characters are the two square brackets, the two curly braces, the colon and the comma.

The grammar counts only four characters as whitespace: space, horizontal tab, line feed and carriage return. Whitespace before the first value and after the last one is also allowed, so leading and trailing blank lines can go too.

Two places are off limits. A space inside a quoted string is part of the value. The number grammar has no room for whitespace at all, so 1 000 is not a number.

How do you remove whitespace from JSON in JavaScript?

In JavaScript, call JSON.stringify(JSON.parse(text)). When you leave out the third argument of JSON.stringify, no white space is used in the output.

const compact = JSON.stringify(JSON.parse(text));

Here is a small order record, formatted with a 2-space indent:

{
  "order": 1042,
  "customer": "Asha Rao",
  "note": "Leave at the  side door",
  "items": [
    {
      "sku": "TB-200",
      "qty": 2
    },
    {
      "sku": "MX-15",
      "qty": 1
    }
  ]
}

After the round trip it is one line:

{"order":1042,"customer":"Asha Rao","note":"Leave at the  side door","items":[{"sku":"TB-200","qty":2},{"sku":"MX-15","qty":1}]}

When I ran this in Node, the text went from 200 characters to 128. That is 72 fewer, or 36% smaller. The space in the customer's name and the double space in the note survive because they sit inside strings.

If the text is not valid JSON, JSON.parse throws a SyntaxError instead of returning a result, so you find out about a broken file before you ship it. The post on Unexpected end of JSON input covers the most common cause.

How do you remove whitespace from JSON in Python?

In Python, pass separators=(',', ':') to json.dumps. By default Python puts a space after every comma and colon, so plain json.dumps output is one line but not compact. The json module documentation says to use that tuple "to eliminate whitespace".

import json

data = json.loads(text)
compact = json.dumps(data, separators=(',', ':'))

Leave indent alone. Its default is None, which inserts no newlines, and any other value brings the line breaks back.

From a terminal you can skip the script. The module's command-line interface has had a --compact option since Python 3.9.

python -m json.tool --compact input.json output.json

How do you remove whitespace from a JSON file with jq?

With jq, run jq -c . input.json > output.json. jq pretty-prints by default. The -c option, short for --compact-output, makes it put each JSON object on a single line instead.

jq -c . input.json > output.json
curl -s https://api.example.com/orders | jq -c .

The . is the identity filter, which passes the input through unchanged. For the other direction, see how to pretty-print JSON with jq.

Why shouldn't you strip spaces with find-and-replace or a regex?

A find-and-replace can't tell whitespace between tokens from whitespace inside a string, so it damages your data. I ran a "delete every whitespace character" regex over the order record above. The output was 122 characters, not 128, and the six missing characters were real data: the customer became "AshaRao" and the note became "Leaveatthesidedoor".

The result is still valid JSON, so nothing throws an error. You find out when a customer's name shows up wrong on a label.

A parser knows where each string starts and ends. Never edit JSON as plain text when a parser is one function call away.

What else changes when you parse and re-serialize JSON?

Parsing and re-serializing can change more than whitespace, and which side effects you get depends on the tool. Check the table before you minify a file that other systems depend on.

Method What it can change besides whitespace
JSON.parse + JSON.stringify Large integers and number formatting
Python json.dumps Non-ASCII characters are escaped by default
jq -c . Numbers with a very large exponent

JavaScript numbers. JSON.parse turns every number into a JavaScript number, and the reference warns that numbers "may lose precision in the process". In my test, this input:

{"id": 9007199254740993, "price": 1.50, "big": 1e3}

came back as {"id":9007199254740992,"price":1.5,"big":1000}. The ID is now a different ID. The other two values are equal, only written differently. If your file holds large IDs, read why JSON.parse loses precision on large numbers first.

Python and non-ASCII text. ensure_ascii defaults to True, so every non-ASCII character is escaped. In my test "Zürich" came out as "Z\u00fcrich". It is the same string once parsed, but the file is longer and harder to read. Pass ensure_ascii=False to keep the characters.

jq numbers. jq works with double-precision numbers internally, but it keeps the original text of a number it has not modified, so jq -c . writes most numbers back exactly as they were. The manual notes that precision is still lost when the exponent is too large.

All three methods share one limitation: they only handle strict JSON. A file with comments or trailing commas fails to parse, and you have to fix that first. The post on whether JSON can have comments explains the options.

What if the JSON still has odd whitespace after minifying?

If stray characters survive minifying, they are probably not JSON whitespace. A non-breaking space pasted from a web page or a document is not one of the grammar's four, so a strict parser rejects it between tokens.

A byte order mark at the start of a file is a similar case. The standard says software must not add one to JSON sent over a network, and parsers are allowed to ignore it, though not all do. If a file fails at position 0 for no visible reason, look for one.

Inside a string, tabs and line breaks are written as escapes such as \t and \n. Minifying keeps those.

Can you remove whitespace from JSON without writing code?

Yes. Paste the JSON into a minifier that runs in your browser and copy the result. The JSON minifier on this site processes the input with JavaScript in the page, and the tool code makes no network requests with it. That matters when the JSON holds customer data or tokens.

A browser tool runs on JavaScript, so very large integers are at risk, as the table shows. For those files I'd use jq -c . instead.

FAQ

Does removing whitespace change the JSON data?

No, as long as only the whitespace between tokens is removed. Spaces, tabs and line breaks around brackets, braces, colons and commas carry no meaning. Spaces inside a quoted string are data and must stay.

Can I remove whitespace from JSON with a regex?

Not safely. A regex that deletes every space also deletes the spaces inside string values, so "Asha Rao" becomes "AshaRao". Parse the JSON and serialize it again instead.

Is minified JSON still valid JSON?

Yes. The JSON grammar allows whitespace around the structural characters but never requires it, so a single-line document with no spaces parses to the same value.

How do I remove whitespace from a JSON file on the command line?

Run jq -c . input.json > output.json. The -c option makes jq print each JSON value on a single line instead of its default pretty-printed output.

Sources