[英]How to convert Json string with key-value pair into string with only values in javascript
How to convert JSON string with key-value pair into string with only values in javascript. 如何在javascript中将具有键值对的JSON字符串转换为仅包含值的字符串。
For example my JSON output looks like this 例如我的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": {}
}
I want to convert it using javascript as 我想使用javascript将其转换为
var details=[
[
"James",
81.4341,
6.328133
],
[
"James",
81.43489,
6.327633
],
[
"Sera",
81.4377,
6.324533
]
];
Is there any way to do this? 有什么办法吗?
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 ;) )
}
$(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);
}
});
Use JSON.parse
to get the object from the JSON string, then access the BearDetails, convert each element to an array, and stringify the new collection again: 使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.