How to convert JSON string with key-value pair into string with only values in javascript.
For example my JSON output looks like this
{
"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
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:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.