修改JSON元素

时间:2018-04-11 05:19:01

标签: javascript json

我的JS脚本中有一个名为rawdata的JSON,我需要操作它。具体来说,我需要将year后半部分的features属性从year: 1718值更改为year: 1819。当前的JSON看起来像:

{
    features: [
            {attributes:{OBJECTID: 464477, uniqueid: 14494171801, property_no: 14494, year: 1718, path: "Business||CBD Works", …}},
            {attributes:{OBJECTID: 464478, uniqueid: 14494171802, property_no: 14494, year: 1718, path: "Roads & Bins||Roading", …}},
            {attributes:{OBJECTID: 464480, uniqueid: 14494171804, property_no: 14494, year: 1718, path: "Parks & Recr||Parks & Bldg", …}},
            {attributes:{OBJECTID: 464481, uniqueid: 14494171806, property_no: 14494, year: 1718, path: "General||Earthquake", …}}
    ]
}

我希望它看起来像:

{
    features: [
            {attributes:{OBJECTID: 464477, uniqueid: 14494171801, property_no: 14494, year: 1718, path: "Business||CBD Works", …}},
            {attributes:{OBJECTID: 464478, uniqueid: 14494171802, property_no: 14494, year: 1718, path: "Roads & Bins||Roading", …}},
            {attributes:{OBJECTID: 464480, uniqueid: 14494171804, property_no: 14494, year: 1819, path: "Parks & Recr||Parks & Bldg", …}},
            {attributes:{OBJECTID: 464481, uniqueid: 14494171806, property_no: 14494, year: 1819, path: "General||Earthquake", …}}
    ]
}

请注意,这是数据的一个子集(因此我不仅仅手动更改它。

我只是设法将所有year值更改为1819和/或由于推送而创建了递归函数。

1 个答案:

答案 0 :(得分:0)

我找到了这样做的方法。可以迭代features'd变量中的数组JSON.parse

var x = '{"Name": "Worm","features":[{"attributes":{"OBJECTID":464477,"uniqueid":14494171801,"property_no":14494,"year":1718,"path":"Business||CBD Works"}},{"attributes":{"OBJECTID":464478,"uniqueid":14494171802,"property_no":14494,"year":1718,"path":"Roads & Bins||Roading"}},{"attributes":{"OBJECTID":464480,"uniqueid":14494171804,"property_no":14494,"year":1718,"path":"Parks & Recr||Parks & Bldg"}},{"attributes":{"OBJECTID":464481,"uniqueid":14494171806,"property_no":14494,"year":1718,"path":"General||Earthquake"}}]}'

var rawdata = JSON.parse(x);
console.log("Input: ");
console.log(rawdata);

for (var i = 0; i < rawdata.features.length; ++i) {
  if (i >= (rawdata.features.length/2)) {
  	rawdata.features[i].attributes.year = 1920;
  }

}
console.log("Output: ");
console.log(rawdata);