When working with JSON data, you may encounter empty null nodes or fields, empty strings or arrays with no elements. Fixing this empty node can make your JSON data more manageable and efficient to work with. In this tutorial you will learn how to remove all empty nodes from a JSON file using JavaScript.
What is JSON?
JSON (JavaScript Object Notation) is a small data exchange format that is easy for humans to read and write, and easy for machines to analyze. It is often used to send data in web applications.
A typical JSON object looks like this:
{ "name": "John", "age": null, "address": "", "hobbies": [] }
in this example, age, address, and hobbies are considered as empty nodes.
Step-by-step instructions
Step 1: Understand what an empty node is
Before we begin, let’s define what we consider an empty node. In this tutorial, an empty node is:
- `null`
- An empty string `””`
- An empty array `[]`
- An empty object `{}`
Step 2: Write a function to remove empty nodes
Let’s write a recursive function that will traverse through the JSON object and remove these empty nodes.
function removeEmptyNodes(obj) { // Check if the current object is an array if (Array.isArray(obj)) { // Filter out empty arrays and recursively call removeEmptyNodes on non-empty elements return obj .map(removeEmptyNodes) .filter(item => !(item === null || item === '' || (Array.isArray(item) && item.length === 0) || (typeof item === 'object' && !Array.isArray(item) && Object.keys(item).length === 0))); } // Check if the current object is an actual object if (typeof obj === 'object' && obj !== null) { // Iterate over the keys of the object Object.keys(obj).forEach(key => { // Recursively call removeEmptyNodes on each key obj[key] = removeEmptyNodes(obj[key]); // Delete the key if it is an empty node if (obj[key] === null || obj[key] === '' || (Array.isArray(obj[key]) && obj[key].length === 0) || (typeof obj[key] === 'object' && !Array.isArray(obj[key]) && Object.keys(obj[key]).length === 0)) { delete obj[key]; } }); return obj; } // Return the object if it's neither an array nor an object return obj; }
Step 3: Test the Function
Let’s test the function with an example JSON object.
const jsonData = { "name": "John", "age": null, "address": "", "hobbies": [], "contact": { "email": "", "phone": null, "social": {} }, "projects": [ { "name": "Project1", "description": "" }, {} ] }; const cleanedData = removeEmptyNodes(jsonData); console.log(JSON.stringify(cleanedData, null, 2));
Step 4: Result
After running the above code, the output should be:
{ "name": "John", "projects": [ { "name": "Project1" } ] }
As you can see, all empty nodes are removed from the JSON data.