delete operator is used to remove an object property.
delete operator does not returns the new object, only returns a boolean: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
Answer from Mihai Alexandru-Ionut on Stack Overflowdelete operator is used to remove an object property.
delete operator does not returns the new object, only returns a boolean: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
There are several ways to do this, lets see them one by one:
- delete method: The most common way
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
console.log(myObject);
- By making key value undefined: Alternate & a faster way:
let myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
myObject.currentIndustry = undefined;
myObject = JSON.parse(JSON.stringify(myObject));
console.log(myObject);
- With es6 spread Operator:
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "test@email.com",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
const {currentIndustry, ...filteredObject} = myObject;
console.log(filteredObject);
Or if you can use omit() of underscore js library:
const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);
When to use what??
If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.
hope this helps :)
What you call your "JSON Object" is really a JSON Array of Objects. You have to iterate over each and delete each member individually:
for(var i = 0; i < jsonArr.length; i++) {
delete jsonArr[i]['YYY'];
}
Another solution that avoids mutating the original array and uses a more modern features (object rest operator & destructuring)
const arr = [
{
XXX: "2",
YYY: "3",
ZZZ: "4"
},
{
XXX: "5",
YYY: "6",
ZZZ: "7"
},
{
XXX: "1",
YYY: "2",
ZZZ: "3"
}
]
// destructure 'YYY' and return the other props only
const newArray = arr.map(({YYY, ...rest}) => rest)
console.log(newArray)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Recursively delete JSON keys
remove key(s) from a json array under javascript - Stack Overflow
How to delete JSON keys from an array with PHP? - Stack Overflow
Delete specific JSON keys
I'm currently working on a project that relies JSON comparison for tests instead of standard equality (yeah, I know). For particular reasons, we ignore part of the JSON when comparing between the expected and the actual value. Currently, the code is something like this:
import qualified Data.HashMap.Strict as H
deleteValues (Object o) = Object
$ H.delete "values" -- Currently removed "values" key.
deleteValues _ = Object H.empty
We had to change our JSON and we added a new key, which we don't want to consider when testing. This key can appear on several positions, not only at the top level like values.
For example, we have something like this:
{
"values": [],
"info": "ok",
"key_to_remove": 0,
"details": null
}
Here the key_to_remove is only at the top level. But we could have something like:
{
"values": [],
"info": "ok",
"key_to_remove": 1,
"details": {
"info": "ok",
"key_to_remove": 2
}
}The nesting can keep going on, and I really would like to avoid manually traversing the object looking and deleting the key.
The idea is to remove all key_to_remove from the JSON object, independent of the position or value that it holds.
Edit: solution:
deleteKey :: Text -> Value -> Value deleteKey k (Object o) = Object $ H.delete k (deleteKey k <$> o) deleteKey k (Array arr) = Array (deleteKey k <$> arr) deleteKey _ v = v
JSON.stringify has an often overlooked parameter called the replacer. It can accept an array of key names to include in the json output:
JSON.stringify(data, ["ID","VERSION"], " "); // FILE is excluded
Snippet
Run the snippet to see the output with and without using the replacer.
let data = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
console.log("Without replacer: ",
JSON.stringify(data, null, " ")
);
console.log("Using replacer: ",
JSON.stringify(data, ["ID","VERSION"], " ")
);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You should not stringify the object before removing the key.
function test() {
var json = {
"ID": "2196",
"VERSION": "1-2022",
"FILE": "2196.docx"
};
// stringify to show in console as string
json = JSON.stringify(json)
console.log("json " + json);
// convert back to object so you can remove the key
json = JSON.parse(json);
delete json['FILE'];
// stringify to show new object in console as string
json = JSON.stringify(json);
console.log("json " + json);
return;
}
test();
Run code snippetEdit code snippet Hide Results Copy to answer Expand
// make array
$array = json_decode($your_json_string, true);
// loop through array
foreach($array as $key => $item){
// unset them
unset($array[$key]["phonenumber"]);
}
// make json again
$json_string_modified = json_encode($array);
OR using reference
// make array
$array = json_decode($your_json_string, true);
// loop through array using reference
foreach($array as &$item){
// unset specific key
unset($item["phonenumber"]);
}
// unset reference
unset($item);
// make json again
// you may remove JSON_PRETTY_PRINT flag, I kept it just to see o/p
$json_string_modified = json_encode($array,JSON_PRETTY_PRINT);
$jsonArray=json_decode($data);
//Remove unvanted props
foreach ($jsonArray as $key=>$row) {
foreach ($row as $prop=>$field) {
if ($prop != 'phonenumber')
$newArray[$key][$prop] = $field;
}
}
$jsonArray=json_encode($newArray);
delete operator is used to remove an object property.
delete operator does not returns the new object, only returns a boolean: true or false.
In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean
value.
How to remove Json object specific key and its value ?
You just need to know the property name in order to delete it from the object's properties.
delete myjsonobj['otherIndustry'];
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
delete myjsonobj['otherIndustry'];
console.log(myjsonobj);
If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.
let value="test";
let myjsonobj = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
}
Object.keys(myjsonobj).forEach(function(key){
if (myjsonobj[key] === value) {
delete myjsonobj[key];
}
});
console.log(myjsonobj);
There are several ways to do this, lets see them one by one:
- delete method: The most common way
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
delete myObject['currentIndustry'];
// OR delete myObject.currentIndustry;
console.log(myObject);
- By making key value undefined: Alternate & a faster way:
let myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
myObject.currentIndustry = undefined;
myObject = JSON.parse(JSON.stringify(myObject));
console.log(myObject);
- With es6 spread Operator:
const myObject = {
"employeeid": "160915848",
"firstName": "tet",
"lastName": "test",
"email": "[email protected]",
"country": "Brasil",
"currentIndustry": "aaaaaaaaaaaaa",
"otherIndustry": "aaaaaaaaaaaaa",
"currentOrganization": "test",
"salary": "1234567"
};
const {currentIndustry, ...filteredObject} = myObject;
console.log(filteredObject);
Or if you can use omit() of underscore js library:
const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);
When to use what??
If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.
hope this helps :)
I wouldn't recommend using regex for such thing, the better choice would be using a library for parsing json, remove the value, and then turn it into a string again.
JSONObject jsonObject = new JSONObject(input);
jsonObject.getJSONObject("expressions").remove("storyId");
String output = jsonObject.toString();
if you really want to use regex, you can use the follow
jsonString.replaceAll("(\\\"storyId\\\"|\\'storyId\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", "");
but just make sure that storyId is really a string, otherwise this regex won't work.
edit: updated my answer, if you want a function that get the parameter to remove with regex,
void replaceAllKeys(String keyName, String jsonAsString) {
String pattern = String.format("(\\\"%s\\\"|\\'%s\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", keyName, keyName);
return jsonAsString.replaceAll(pattern, "");
}
First i am assuming you will get all json object in jsonObj and then call remove() by passing your json key like following:
jsonObj.getAsJsonObject("expressions").remove("storyId");
Damn, forget about jQuery! This is a pure javascript task.
- To loop through an Array, use
for (var i=0; i<array.length; i++), to loop over an Object usefor (var i in object) - To delete an array entry, use
splice(). To delete an object attribute, usedelete object[key];. - To filter an Array, in modern javascript versions you can use
filter()with a callback function for every entry; it creates a new Array. There is no such (native) method for objects.
You may find some libraries with helpful utility functions, like underscore. But to learn JS, it may be better to do it with native methods first.
Underscore.js is the library to use for all things data. Functions that will be useful for your data are; each, reject and groupBy.
jsonObj.getJSONArray("Data").get(0).remove("status);
#Updated Code-breakdown:
JSONObject obj= (JSONObject) jsonObj.getJSONArray("Data").get(0);
obj.remove("status");
JSONArray newArr=new JSONArray();
newArr.put(obj);
jsonObj.put("Data", newArr);
It should do your work, haven't tested though.
First, your Data is JSONArray, retrieving that by jsonObj.getJSONArray("Data"), then access the array with get(0)[assuming, your array will contain only one entry like your example] and finally, removing that key by remove method.
You need to iterate over Data property which is a JSON Array and remove for every item status key.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.File;
import java.io.FileReader;
public class JsonSimpleApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(jsonFile));
JSONArray dataArray = (JSONArray) root.get("Data");
dataArray.forEach(item -> {
JSONObject object = (JSONObject) item;
object.remove("status");
});
System.out.println(root);
}
}
Above code prints:
{"Data":[{"Id":"1358","isActive":true}],"actionName":"test"}