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.
A response with many empty fields wastes bytes on keys that carry no information. A replacer function can leave them out while serializing.
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);{"id":7,"name":"Ada","nickname":null,"bio":null,"website":"https://example.test"}
{"id":7,"name":"Ada","website":"https://example.test"}
81 53Returning 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.