可能重复:
JSON to javaScript array
有人能指出我如何使用java脚本将json数据转换为数组,以便从de数据中绘制图表。 JSON的结构如下:
{
"d":{
"results":[
{
"_metadata":{
"uri": "http://www.something.com/hi",
"type" : "something.preview.hi"
}, "Name", "Sara", "Age": 20, "Sex" : "female"
},
"_metadata":{
"uri": "http://www.something.com/hi",
"type" : "something.preview.hi"
}, "Name", "James", "Age": 20, "Sex" : "male"
}
]
}
}
我想将此jason转换为以下格式:
var sampleData = [
{ name: 'Sara', Age: 20, Sex: 'female'},
{ name: 'James', Age: 20, Sex: 'male'}
];
有没有人对如何实现这一点有任何建议?
答案 0 :(得分:8)
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ name: result.Name, Age: result.Age, Sex: result.Sex });
}
答案 1 :(得分:1)
您只需在javascript对象中遍历结果数组,然后构建一个包含所需格式数据的新数组。
var results = data.d.results;
var sampleData = [], item;
for (var i = 0, len = results.length; i < len; i++) {
item = results[i];
sampleData.push({name: item.Name, Age: item.Age, Sex: item.Sex});
}