删除 JSON 元素

2022-08-30 04:09:13

我想从JSON中删除JSON元素或整行。

我有以下JSON字符串:

{
   "result":[
       {
           "FirstName": "Test1",
           "LastName":  "User",
       },
       {
           "FirstName": "user",
           "LastName":  "user",
       },
       {
           "FirstName": "Ropbert",
           "LastName":  "Jones",
       },
       {
           "FirstName": "hitesh",
           "LastName":  "prajapti",
       }
   ]
}

答案 1
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.

可以使用拼接从数组中删除元素。


答案 2

OBJECT 中不要有尾随逗号(JSON 是一种字符串表示法)

更新:如果要从对象的数组中删除项目,则需要使用 array.splice 而不是删除。或者,在删除后筛选数组以查找未定义

var data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}
console.log(data.result);
console.log("------------ deleting -------------");
delete data.result[1];
console.log(data.result); // note the "undefined" in the array.


data = {
  "result": [{
    "FirstName": "Test1",
    "LastName": "User"
  }, {
    "FirstName": "user",
    "LastName": "user"
  }]
}

console.log(data.result);
console.log("------------ slicing -------------");
var deletedItem = data.result.splice(1,1);
console.log(data.result); // here no problem with undefined.