Skip to content
jshacks.dev
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read
Summarize in AI

A response with many empty fields wastes bytes on keys that carry no information. A replacer function can leave them out while serializing.

payload.jsJavaScript
const user = {
  id: 7,
  name: 'Ada',
  nickname: null,
  bio: null,
  website: 'https://example.test',
};

const full = JSON.stringify(user);
const slim = JSON.stringify(user, (key, value) => (value === null ? undefined : value));

console.log(full);
console.log(slim);
console.log(full.length, slim.length);
Text
{"id":7,"name":"Ada","nickname":null,"bio":null,"website":"https://example.test"}
{"id":7,"name":"Ada","website":"https://example.test"}
81 53

Returning undefined from a replacer removes that property. The two sample lengths show the saving for this tiny object. With compression, repeated keys shrink a lot already, so the real gain on the wire is smaller than the raw numbers suggest.

The cost is in meaning: a missing key and an explicit null are different, and a client that reads user.nickname === null will now get undefined. Pick one rule, document it in the API, and test the clients. A replacer also runs for every nested value, so for huge payloads a dedicated serializer or a schema can be faster. See JSON.stringify.

Also inAPIs
Taggednode 24
Share

More snippets

APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.