JSON Minification — Remove Whitespace and Reduce Payload Size
Minifying JSON removes all whitespace and produces compact payloads for API responses and storage. Learn how to minify JSON in JavaScript, Python, and at the server level with...
Minified JSON removes all whitespace — spaces, tabs, newlines — to produce the most compact representation. The difference matters in high-volume APIs and embedded systems with limited bandwidth.
Format or minify JSON with the JSON Formatter.
JSON minification in JavaScript
// The simplest minifier: parse then re-stringify without spaces
function minifyJSON(jsonString) {
return JSON.stringify(JSON.parse(jsonString));
}
// Example:
const pretty = `{
"name": "Alice",
"age": 30,
"roles": [
"admin",
"editor"
]
}`;
minifyJSON(pretty);
// '{"name":"Alice","age":30,"roles":["admin","editor"]}'
The re-parse approach also validates the JSON — if it’s malformed, JSON.parse throws.
How much space does minification save?
const pretty = JSON.stringify(data, null, 2);
const minified = JSON.stringify(data);
const savings = (1 - minified.length / pretty.length) * 100;
console.log(`Savings: ${savings.toFixed(1)}%`);
// Typical: 15–35% for shallow objects, up to 60% for deeply nested data
For comparison, gzip compression typically achieves 60–90% reduction on JSON. Minification alone is much less effective — but minification + gzip is better than gzip alone.
Minify JSON in Python
import json
def minify_json(json_string: str) -> str:
"""Remove all whitespace from JSON."""
parsed = json.loads(json_string)
return json.dumps(parsed, separators=(',', ':'))
# Example with file:
with open('data.json') as f:
data = json.load(f)
minified = json.dumps(data, separators=(',', ':'))
# separators=(',', ':') removes space after : and ,
Minify JSON files in Node.js
import { readFileSync, writeFileSync } from 'fs';
import { glob } from 'glob'; // npm install glob
async function minifyJSONFiles(pattern = '**/*.json') {
const files = await glob(pattern, { ignore: 'node_modules/**' });
let total = 0;
let saved = 0;
for (const file of files) {
try {
const original = readFileSync(file, 'utf8');
const minified = JSON.stringify(JSON.parse(original));
total += original.length;
saved += original.length - minified.length;
writeFileSync(file, minified);
console.log(`Minified: ${file}`);
} catch (e) {
console.error(`Failed: ${file} — ${e.message}`);
}
}
console.log(`Saved ${saved} of ${total} bytes (${(saved/total*100).toFixed(1)}%)`);
}
minifyJSONFiles('dist/**/*.json');
Express: send minified JSON by default
import express from 'express';
const app = express();
// Express sends minified JSON by default:
app.get('/api/user', (req, res) => {
res.json({ name: 'Alice', age: 30 });
// Automatically: '{"name":"Alice","age":30}'
});
// To send pretty JSON in development:
if (process.env.NODE_ENV !== 'production') {
app.set('json spaces', 2);
}
// Or use json-stringify-safe for circular reference safety:
// npm install json-stringify-safe
import stringify from 'json-stringify-safe';
res.send(stringify(data));
Nginx: gzip compression for JSON APIs
# nginx.conf
gzip on;
gzip_types application/json text/plain application/javascript;
gzip_min_length 1000; # Only compress responses > 1KB
gzip_comp_level 6; # 1-9, higher = slower but smaller
gzip_vary on;
gzip_proxied any;
add_header Vary Accept-Encoding;
# For Brotli (better than gzip, supported by all modern browsers):
brotli on;
brotli_types application/json;
brotli_comp_level 6;
Content-Encoding negotiation
// Client: request compressed response
const res = await fetch('/api/data', {
headers: { 'Accept-Encoding': 'gzip, deflate, br' }
});
// Response is automatically decompressed by the browser/fetch API
// Node.js: fetch with compression
import { createGunzip } from 'zlib';
import { pipeline } from 'stream/promises';
async function fetchCompressedJSON(url) {
const res = await fetch(url, {
headers: { 'Accept-Encoding': 'gzip' }
});
const encoding = res.headers.get('Content-Encoding');
if (encoding === 'gzip') {
// Node.js fetch doesn't decompress automatically in all versions
// Use node-fetch or Axios which handles this correctly
}
return res.json();
}
JSON size reduction strategies (ordered by impact)
| Strategy | Typical reduction | Complexity |
|---|---|---|
| Gzip/Brotli compression | 60–90% | Low (server config) |
| Remove whitespace | 15–35% | None |
| Shorten key names | 10–30% | High (API contract change) |
| Use arrays instead of objects | 5–20% | Medium |
| Omit null/empty fields | 5–15% | Low |
| Binary formats (MessagePack, CBOR) | 30–50% vs minified JSON | High |
Related tools
- JSON Formatter — format or minify JSON online
- HTML Minifier — minify HTML responses
- Image Compressor — compress image payloads
Related posts
- What Is JSON and Why You Should Always Format It — JSON is the universal data format of the modern web. This is what it actually is…
- The 10 Most Common JSON Validation Errors (and How to Fix Them) — Every JSON parse error in production traces back to one of ten root causes. This…
- JSON Beautifier — Format and Prettify JSON Instantly — A JSON beautifier adds proper indentation and line breaks to minified JSON, maki…
- JSON Formatter — Why Formatting JSON Matters and How It Works — A JSON formatter takes compact, hard-to-read JSON and adds whitespace and indent…
- JSON.stringify Options — replacer, space, and Circular Reference Handling — JSON.stringify accepts three arguments: value, replacer, and space. Learn how to…
Related tool
Format, validate, and beautify JSON online. 100% client-side — your data never leaves your browser.
Written by Mian Ali Khalid. Part of the Data & Format pillar.