如何将带键值对的JSON字符串转换为仅包含javascript值的字符串。
例如,我的JSON输出看起来像这样
{
"data": {
"BearCollection": {
"BearDetails": [
{
"Name": "James",
"x": "81.43410000",
"y": "6.32813300"
},
{
"Name": "James",
"x": "81.43489000",
"y": "6.32763300"
},
{
"Name": "Sera",
"x": "81.4377000",
"y": "6.32453300"
}
]
}
},
"xhr": {}
}
我想使用javascript转换它
var details=[
[
"James",
81.4341,
6.328133
],
[
"James",
81.43489,
6.327633
],
[
"Sera",
81.4377,
6.324533
]
];
有没有办法做到这一点?
答案 0 :(得分:1)
var json = "Your JSON string";
obj = JSON.parse(json);
for(int i= 0; i< obj.data.BearCollection.BearDetails.length;i++)
{
String Name = obj.data.BearCollection.BearDetails[i].Name;
String x = obj.data.BearCollection.BearDetails[i].x;
String y = obj.data.BearCollection.BearDetails[i].y;
..fill Array (pseudo - do some work yourself ;) )
}
答案 1 :(得分:0)
$(document).ready(function() {
var data = JSON.parse('{"data": {"BearCollection": {"BearDetails": [{"Name": "James","x": "81.43410000","y": "6.32813300"},{"Name": "James","x": "81.43489000","y": "6.32763300"},{"Name": "Sera","x": "81.4377000","y": "6.32453300"}]}},"xhr": {}}');
var bear;
var arr = [];
var nestedArr;
for (i in data.data.BearCollection.BearDetails) {
bear = data.data.BearCollection.BearDetails[i];
nestedArr = [];
nestedArr.push(bear.Name);
nestedArr.push(bear.x);
nestedArr.push(bear.y);
arr.push(nestedArr);
}
});
答案 2 :(得分:0)
使用JSON.parse
从JSON字符串中获取对象,然后访问BearDetails,将每个元素转换为数组,并再次对新集合进行字符串化:
var obj = JSON.parse(jsonstring);
var details = obj.data.BearCollection.BearDetails.map(function(detail) {
return [detail.Name, detail.x, detail.y];
});
return JSON.stringify(details);