0

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
2
  • Hi kamesh it is jquery json object Commented Jul 3, 2014 at 10:14
  • I believe the OP has forgotten to add node.js as a tag Commented Jul 3, 2014 at 10:15

3 Answers 3

2

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)
}
Salman
9,4676 gold badges42 silver badges74 bronze badges
answered Jul 3, 2014 at 10:15
Sign up to request clarification or add additional context in comments.

3 Comments

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?
You want to fetch array instead of JSON from ajax? then will have to do on server side
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"
0

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

1 Comment

Hi Girish, Thanks for reply but this is not functioning,
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.