X Xerobit

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...

Mian Ali Khalid · · 4 min read
Use the tool
JSON Formatter
Format, validate, and beautify JSON online. 100% client-side — your data never leaves your browser.
Open JSON Formatter →

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)

StrategyTypical reductionComplexity
Gzip/Brotli compression60–90%Low (server config)
Remove whitespace15–35%None
Shorten key names10–30%High (API contract change)
Use arrays instead of objects5–20%Medium
Omit null/empty fields5–15%Low
Binary formats (MessagePack, CBOR)30–50% vs minified JSONHigh

Related posts

Related tool

JSON Formatter

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.