Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Delete Data from JSON Using a Key in React

This guide explains the steps to parse JSON data and perform the delete operation on a nested JSON object using a key as input.

Nov 9, 2020 • 4 Minute Read

Introduction

JavaScript Object Notation (JSON) is a widely popular key-value-based data format used to store and transfer data. JSON uses basic data types, such as string, boolean, int, decimal, object, arrays, and null, to transfer data using predefined hierarchy and key-value pairs. Due to its concise structure and durability, JSON is supported by most development platforms, No-SQL databases, REST, GraphQL, and so on.

A JSON string can easily be converted to a JavaScript object by using JSON API to directly access the data by using dot notation and keys. The inbuilt JSON support allows you to easily integrate REST APIs, data management, and dynamic component design in React. This guide explains the steps to parse JSON data and perform the delete operation on a nested JSON object using a key as input.

Create a JSON Object

A JSON object is represented using a pair of curly braces ({}), and the key-value is separated by using a colon (:). A JSON string can be created using a combination of single and double quotes:

      let jsonStr = '{"name":"ABC", "age":10 }';
    

Note: JSON strings must only use double quotes to wrap key and values. Use single quotes to wrap a JSON string. The jsonStr can be converted to a JavaScript object using the parse method:

      let jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.name, jsonObj.age); // ABC : 10
    

The eval function is also used for parsing:

      let jsonObj = eval('('+jsonStr+')');
    

The use of eval is not recommended because eval can used as a loophole to run malformed instructions, though unlike the parse function, eval can transform a JSON string wrapped in double quotes:

      let jsonObj = eval('('+ "{'name':'ABC', 'age':10 }" +')');
    

Delete Data from JSON String using Regular Expressions

Regular expressions can be used to find and replace a specific portion of a string using the replace function. A pair of double quotes with key can be used to create a pattern:

      let jsonStr = '{"name":"ABC", "age":10 }';
let key = "age";
let cleanJsonRegex = new RegExp(`,.*${key}.*[, ]`, "g");
let nameJsonStr = jsonStr.replace(cleanJsonRegex, "");
console.log(nameJsonStr); // "{\"name\":\"ABC\"}"
    

The cleanJsonRegex object defines the pattern to match a specific key-value pair, and it can be explained as:

  • , match a comma character
  • .* match zero or more character except for line terminators (\n)
  • ${key}.* match the exact value of key and zero or more characters after the key
  • [, ] match either a comma or space
  • g flag will match all possible matches in the jsonStr

The replace function finds and replaces the matched data from the jsonStr and returns a resultant string.

Note: Regular expressions are quite powerful but they are also fragile so always avoid the use of regular expressions with complex data.

Delete Data from JSON using JavaScript Objects

JavaScript objects offer a convenient way to access JSON data using dot notation and indexes for JSON arrays. Use the parse function to convert a JSON string to JavaScript object:

      let jsonStr = '{"name":"ABC", "age":10, "phone":["1234567890","1234567890"]}';
let jsonObj = JSON.parse(jsonStr);
    

The delete operator can be used to remove a key-value pair from a JavaScript object:

      delete jsonObj.name;
/* after delete
{
  age: 10,
  phone: ["1234567890", "1234567890"]
}
*/
    

Alternately, string keys can be used to delete a key-value pair:

      let key = 'name';
delete jsonObj[key];
    

The advantage of using string keys with a JavaScript object is that it allows the use of keys having special characters:

      delete jsonObj['class.name'];
    

Tips

• Use stringify to covert a JavaScript object to a JSON string:

      let obj = {name: "ABC"};
console.log(JSON.stringify(obj));
    

• Use toJSON to get string representation of date objects. • For better support, use typescript for static type checking support.

Conclusion

JSON and JavaScript objects have almost the same syntax and inbuilt browser support to parse JSON string as a JavaScript object. Always prefer the use of JavaScript objects to access JSON data. Happy coding!