Javascript删除JSON元素

时间:2012-12-26 18:03:02

标签: php javascript json

我在PHP页面中有这个JSON字符串:

{
  "elements": [{
    "type": "pie",
    "alpha": 0.3,
    "animate": [{
      "type": "fade"
    }, {
      "type": "bounce",
      "distance": 5
    }],
    "start-angle": 0,
    "tip": "#val# de #total# #percent#",
    "colours": ["#d01f3c", "#356aa0", "#C79810"],
    "values": [{
      "value": 1,
      "label": "procesador amd sempron 140"
    }, {
      "value": 1,
      "label": "procesador sempron le130"
    }, {
      "value": 1,
      "label": "procesador amd a4-3300 x2"
    }, {
      "value": 1,
      "label": "procesador intel celeron g530"
    }]
  }],
  "title": {
    "text": "Procesadores, Reinicio",
    "style": "color: #356aa0; font-size: 20px"
  },
  "bg_colour": "#FFFFFF",
  "x_axis": null
}

我称之为:

$.getJSON("restart_proce.php", function(json)
{    
console.log(json);

我需要将其转换为:

[{\"value\": 1, \"label\": \"procesador amd sempron 140\" }, { \"value\": 1, \"label\": \"procesador sempron le130\" }, { \"value\": 1, \"label\": \"procesador amd a4-3300 x2\" }, { \"value\": 1, \"label\": \"procesador intel celeron g530\" } ]

我正在尝试删除这样的元素:

delete json.elements[3];

但它不会删除任何内容。我怎样才能使它发挥作用?

4 个答案:

答案 0 :(得分:2)

试试这个:

json.elements.splice(3, 1);

请参阅:Array.splice

答案 1 :(得分:2)

从数组中删除项目:

有几种方法。 splice 方法是最通用的方法:

data.items.splice(3, 1); // Removes three items starting with the 2nd,

splice修改原始数组,并返回您删除的项目数组。

答案 2 :(得分:1)

只需在console.log(json)

之前直接修改这些值
json= json.elements[0].values

或者在restart_proce.php php页面中只是echo

echo json_encode($data['elements'][0]['values']); // if associative array is used.

答案 3 :(得分:0)

试试这个:

var data = {"result":[
  {"FirstName":"Test1","LastName":"User","Email":"test@test.com","City":"ahmedabad","State":"sk","Country":"canada","Status":"False","iUserID":"23"},
  {"FirstName":"user","LastName":"user","Email":"u@u.com","City":"ahmedabad","State":"Gujarat","Country":"India","Status":"True","iUserID":"41"},
  {"FirstName":"Ropbert","LastName":"Jones","Email":"Robert@gmail.com","City":"NewYork","State":"gfg","Country":"fgdfgdfg","Status":"True","iUserID":"48"},
  {"FirstName":"hitesh","LastName":"prajapti","Email":"hitesh.prajapati@phptalent.com","City":"","State":"","Country":"","Status":"True","iUserID":"78"}
  ]
}
alert(data.result);
delete data.result[3];
alert(data.result);

工作JSFiddle

或者您可以使用splice从数组中删除元素。