How to Minify JSON to One Line and Why Sorted Keys Help

When compact single-line JSON is useful, how to minify it with JavaScript, jq or Python, why sorted keys give stable output, and number-precision traps.

Updated September 29, 2026 5 min read

Use the free JSON MinifierValidate and compress JSON to a single line, optionally sorting keys

Pretty-printed JSON is made for people. Two-space indentation, one key per line and neatly nested arrays make a config file or API response easy to scan. But the moment that JSON has to live somewhere else, such as an environment variable, a single database column, a log line, a URL parameter or an HTML attribute, all those line breaks become a problem rather than a help.

This guide covers when compact JSON is the right format, how to produce it safely, why sorting keys turns JSON into a stable fingerprint, and the precision trap that catches people who minify with a JavaScript parser.

What minifying JSON actually changes

JSON allows whitespace between tokens, and none of it carries meaning. Minifying removes every space, tab and newline outside of strings:

{
  "id": "ord_20931",
  "paid": true,
  "tags": [ "gift", "express" ]
}

becomes

{"id":"ord_20931","paid":true,"tags":["gift","express"]}

Whitespace inside strings is data and stays untouched. Minification does not shorten keys, drop null values or change numbers on purpose; the result is the same document with less padding.

Where single-line JSON is the right choice

  • Environment variables and secrets managers. Many systems handle multi-line values badly, so a service account key or feature-flag object is easier to store on one line.
  • Log lines and JSON Lines files. Formats such as NDJSON put one complete JSON document per line. A line break inside a record would split it in two.
  • Database columns and cache values. Compact text uses less storage and is quicker to compare.
  • Embedding in HTML or scripts. A data-config attribute or an inline script is simpler with one line.
  • API payloads. Less data per request, although gzip on the connection already removes most of the whitespace overhead.

For files that humans edit, such as package.json or a settings file, keep the pretty version. Minified config is painful to review in a pull request.

Sorted keys: turning JSON into a fingerprint

Two JSON objects can be equal in meaning but different as text, simply because the keys appear in a different order. That breaks any comparison that works on strings: cache keys, checksums, deduplication and "has this changed?" checks.

The fix is a canonical form: sort the keys at every level, keep array order (because order in arrays is meaningful), and remove all whitespace. Here is a small, runnable Node.js version:

import { createHash } from "node:crypto";

function canonical(value) {
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
  if (value && typeof value === "object") {
    const keys = Object.keys(value).sort();
    return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(",")}}`;
  }
  return JSON.stringify(value);
}

const a = { plan: "pro", seats: 5, tags: ["b", "a"] };
const b = { seats: 5, tags: ["b", "a"], plan: "pro" };

console.log(JSON.stringify(a) === JSON.stringify(b)); // false
console.log(canonical(a) === canonical(b));           // true
console.log(createHash("sha256").update(canonical(a)).digest("hex").slice(0, 16));

Hashing the canonical string gives you a stable identifier for the content, no matter who produced the JSON or in which order they wrote the keys. For strict interoperability between languages there is a formal standard, the JSON Canonicalization Scheme (RFC 8785), which also pins down number and string formatting.

Minify JSON in your browser

The JSON Minifier does the parsing, sorting and size comparison for you, without uploading anything.

  1. Open the JSON Minifier and paste your data into JSON input, click Open file to load a .json file, or try Load sample.
  2. If the input is not valid JSON, the tool shows the error with its line and column instead of producing broken output. Fix it and the result appears.
  3. Switch on Sort keys A–Z if you want the canonical, alphabetically ordered form described above. Arrays keep their order.
  4. Check the size tiles (Original size, Minified size, Saved, Gzipped), then click Copy or Download.

Because the minifier parses before it writes, it doubles as a quick syntax check. For a detailed error view with the surrounding lines highlighted, use the JSON Validator; to go the other way and make compact JSON readable, use the JSON Formatter. The guide How to Format JSON and Fix the Most Common Syntax Errors covers the typical errors in depth.

Other ways to minify JSON

JavaScript or Node.js. JSON.stringify(JSON.parse(text)) produces minified output in one line. Add the canonical function above if you need sorted keys.

jq on the command line. The -c flag prints compact output and -S sorts keys:

jq -c . order.json > order.min.json
jq -cS . order.json > order.canonical.json

jq is the best option for scripts and large files, and it is preinstalled on many Linux systems.

Python. From Python 3.9 onwards the built-in module has a compact mode: python -m json.tool --compact --sort-keys order.json.

Your editor. Several code editors have a "join lines" or JSON extension command. Fine for small files, but easy to get wrong with long strings.

Pitfalls to watch for

Large integers lose precision

Any tool that parses JSON into JavaScript numbers is limited to integers up to 2^53 − 1. Larger IDs are silently rounded:

JSON.stringify(JSON.parse('{"id": 12345678901234567890, "price": 1.50}'));
// '{"id":12345678901234567000,"price":1.5}'

The id has changed, and 1.50 has become 1.5. The second is harmless; the first can break lookups. If your data contains 64-bit IDs, ask the API to send them as strings, or use a tool that preserves numbers as text, such as jq 1.7 or later.

Duplicate keys

JSON parsers usually keep the last value when a key appears twice in one object. Minifying such a document therefore silently drops the earlier value. Treat duplicate keys as a bug in the source.

Minified JSON is not smaller once gzipped by much

On an HTTP response that is already compressed, the saving from minifying is modest. Minify when line breaks cause problems or when storage size matters, not purely for transfer speed.

Frequently asked questions

Does minifying JSON change the data?

No. Only whitespace outside strings is removed. The one exception is number formatting when a JavaScript parser is used: very large integers can be rounded and trailing zeros such as 1.50 are dropped.

Is minified JSON still valid JSON?

Yes. Whitespace between tokens is optional in the JSON grammar, so a single-line document is just as valid as an indented one.

Why would I sort JSON keys?

Sorting gives the same text for the same data, regardless of the order keys were written. That makes JSON suitable for hashing, caching, deduplication and simple text comparison.

Does sorting keys change array order?

It should not. Array order is meaningful in JSON, so a correct canonical form only sorts object keys and leaves arrays exactly as they are.

How do I put JSON in an environment variable?

Minify it to one line, then wrap it in single quotes in a shell or .env file so that double quotes inside the JSON are not interpreted. Many platforms also accept Base64-encoded values, which avoids quoting issues entirely.

Try it now: JSON Minifier

Loading tool…