How can I load a regular array from a JSON Response like this:
{"project":"8","powerline":"188.396496","road":"7.876766","cost":"69885005.45"}
to
var cars = [8, 188.396496, 7.876766, 69885005.45];
I already tried something like this:
req.done(function(data) {
var cars = JSON.parse(data);
});
but it is not doing the job.
halfer
20.2k20 gold badges111 silver badges208 bronze badges
asked Jul 3, 2014 at 10:09
Mona Coder
6,31218 gold badges71 silver badges140 bronze badges
-
Hi kamesh it is jquery json objectMona Coder– Mona Coder2014年07月03日 10:14:34 +00:00Commented Jul 3, 2014 at 10:14
-
I believe the OP has forgotten to add node.js as a tagSalman– Salman2014年07月03日 10:15:57 +00:00Commented Jul 3, 2014 at 10:15
3 Answers 3
You can simply run a for..in loop like this. and keep pushing the values into a new array.
var obj = {
"project" : "8",
"powerline" : "188.396496",
"road" : "7.876766",
"cost" : "69885005.45"
}
var arr = [];
for (var key in obj) {
var val = parseFloat("0" + obj[key]);
arr.push(val)
}
Sign up to request clarification or add additional context in comments.
3 Comments
Mona Coder
Hi rajub, thanks for reply but as I already mentioned I am getting the JSON from a Ajax request so how I can use your approach?
rajub
You want to fetch array instead of JSON from ajax? then will have to do on server side
Mona Coder
besides, it is loading the keys as STRING into the array. Is there any way to force them be populate as Numbers like 8 instead of "8"
You can manipulate JSON object as Array, please try this way
req.done(function(data) {
var cars = $.map(JSON.parse(data), function(value, index){
return i;
});
console.log(cars);
});
answered Jul 3, 2014 at 10:15
Girish
12.2k3 gold badges37 silver badges54 bronze badges
1 Comment
Mona Coder
Hi Girish, Thanks for reply but this is not functioning,
That's because you're getting an object when you're calling JSON.parse. You can run the following to get the values without keys:
req.done(function (data) {
var jsonData = JSON.parse(data),
cars = []
for (var key in jsonData) {
cars.push(jsonData[key])
}
})
answered Jul 3, 2014 at 10:16
Aeveus
5,4323 gold badges32 silver badges42 bronze badges
Comments
lang-js