Javascript 通过javascript将json转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10518313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert json to array via javascript
提问by wingman55
Possible Duplicate:
JSON to javaScript array
可能的重复:
JSON 到 javaScript 数组
Can anybody point me out how i can convert a json data to an array using java script in order to draw a chart from de data. The JSON is structured as follows:
任何人都可以指出我如何使用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"
}
]
}
}
I would like to convert this jason to the following format:
我想将此杰森转换为以下格式:
var sampleData = [
{ name: 'Sara', Age: 20, Sex: 'female'},
{ name: 'James', Age: 20, Sex: 'male'}
];
Does anyone have any advice on how to achieve this?
有没有人对如何实现这一目标有任何建议?
回答by jmar777
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 });
}
回答by jfriend00
You just have to iterate through the results array in your javascript object and build a new array that has the data in the format you want.
您只需要遍历 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});
}