How to Clean JSON Data: Remove Empty Values and Nulls
API responses are messy. You get back a bunch of null values, empty strings, and fields that exist but contain nothing useful. Before you store that data or pass it along, you'll probably want to clean it up.
Here's how to strip out the cruft from your JSON, whether you want a quick automated solution or need to write custom cleaning logic.
Why Clean JSON Data?
A few reasons you might want to remove empty values:
- Smaller file sizes. Less data means faster transmission and lower storage costs.
- Cleaner debugging. When you're logging or inspecting data, nulls and empty strings add noise.
- Database compatibility. Some systems treat empty strings differently from null, causing issues.
- API requirements. Downstream services might reject or mishandle empty values.
- Data quality. Clean data is easier to analyze and less likely to cause bugs.
What to Remove
"Empty" can mean different things depending on your needs. Here's what most people want to strip out:
Definitely remove
nullvalues- Empty strings
"" - Empty arrays
[] - Empty objects
{}
Maybe remove (depends on context)
0(zero is often a valid value)false(booleans are usually meaningful)- Whitespace only strings
" " - Objects with only null values inside
Example: before and after
// Before cleaning
{
"user": {
"name": "Alice",
"nickname": null,
"bio": "",
"age": 28,
"tags": [],
"settings": {
"theme": "dark",
"notifications": null
}
},
"meta": {}
}
// After cleaning
{
"user": {
"name": "Alice",
"age": 28,
"settings": {
"theme": "dark"
}
}
}
See how much cleaner that is? Same information, less noise.
Quick Solution: Use a Tool
If you just need to clean some JSON quickly, don't write code. Use our JSON cleaner tool. Paste your JSON, click Clean, done.
It removes:
- null values
- Empty strings
- Empty arrays and objects
- Recursively handles nested structures
Everything happens in your browser, so your data never leaves your machine. Good for quick cleanups or when you're dealing with sensitive data.
Cleaning JSON in JavaScript
Need to clean JSON in your code? Here's a simple approach:
Basic cleaning (one level)
function cleanObject(obj) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
// Skip null, undefined, empty strings
if (value === null || value === undefined || value === '') {
continue;
}
// Skip empty arrays
if (Array.isArray(value) && value.length === 0) {
continue;
}
// Skip empty objects
if (typeof value === 'object' && Object.keys(value).length === 0) {
continue;
}
result[key] = value;
}
return result;
}
// Usage
const dirty = { name: "Alice", bio: "", age: 28, tags: [] };
const clean = cleanObject(dirty);
// { name: "Alice", age: 28 }
Using lodash
If you're already using lodash, there's a one liner:
const _ = require('lodash');
// Remove null, undefined, empty strings
const clean = _.omitBy(obj, (v) => v === null || v === '' || v === undefined);
// Or for deep cleaning with pickBy
const deepClean = _.pickBy(obj, _.identity);
Cleaning JSON in Python
Python makes this pretty easy with dictionary comprehensions:
Basic cleaning
def clean_dict(d):
"""Remove None, empty strings, empty lists, empty dicts."""
return {
k: v for k, v in d.items()
if v is not None
and v != ''
and v != []
and v != {}
}
# Usage
dirty = {"name": "Alice", "bio": "", "age": 28, "tags": []}
clean = clean_dict(dirty)
# {"name": "Alice", "age": 28}
Deep cleaning with recursion
def deep_clean(obj):
"""Recursively remove empty values from nested structures."""
if isinstance(obj, dict):
cleaned = {}
for k, v in obj.items():
cleaned_v = deep_clean(v)
if cleaned_v is not None and cleaned_v != '' and cleaned_v != [] and cleaned_v != {}:
cleaned[k] = cleaned_v
return cleaned if cleaned else None
elif isinstance(obj, list):
cleaned = [deep_clean(item) for item in obj]
cleaned = [item for item in cleaned if item is not None and item != '' and item != []]
return cleaned if cleaned else None
return obj
Deep/Recursive Cleaning
Real world JSON is nested. You've got objects inside objects inside arrays. A simple flat cleaning won't cut it.
JavaScript recursive version
function deepClean(obj) {
if (Array.isArray(obj)) {
// Clean array items recursively, filter out empty results
const cleaned = obj
.map(item => deepClean(item))
.filter(item => !isEmpty(item));
return cleaned.length ? cleaned : undefined;
}
if (obj !== null && typeof obj === 'object') {
// Clean object properties recursively
const cleaned = {};
for (const [key, value] of Object.entries(obj)) {
const cleanedValue = deepClean(value);
if (!isEmpty(cleanedValue)) {
cleaned[key] = cleanedValue;
}
}
return Object.keys(cleaned).length ? cleaned : undefined;
}
// Return primitives as is
return obj;
}
function isEmpty(value) {
return value === null
|| value === undefined
|| value === ''
|| (Array.isArray(value) && value.length === 0)
|| (typeof value === 'object' && Object.keys(value).length === 0);
}
This handles deeply nested structures and removes empty containers that become empty after their contents are cleaned.
Edge Cases to Watch Out For
Zero is not empty
Don't accidentally filter out 0. It's a valid number. Same with
false.
// BAD - filters out 0 and false
if (!value) continue;
// GOOD - explicitly check for empty values
if (value === null || value === '') continue;
Whitespace strings
Should " " be considered empty? Usually yes. Trim it first or check
specifically:
if (typeof value === 'string' && value.trim() === '') continue;
Date objects
If you have Date objects in your data, they might get filtered out as empty objects. Handle them separately.
Circular references
If your object has circular references (A points to B, B points to A), recursive cleaning will cause infinite loops. You'll need to track visited objects.
Preserving structure
Sometimes you want to keep the keys but just set them to null rather than removing them entirely. This preserves the schema:
// Instead of removing, normalize to null
if (value === '' || value === undefined) {
result[key] = null;
}