1

Possible Duplicate:
How might I extract the property values of a JavaScript object into an array?

So i have a json array served from a very simple server as an array to my local server. I wish to parse the data into javascript for intended use in my web-app.

How would i convert a JSONP array to a javascript array? and lose the 'names' within JSON.

e.g.

myjsoncallback({"h1": "cmPanel", "h2" : "cmAuto", "h3": 0})

to become

(["cmPanel","cmAuto",0])

Thanks in advance stack, as always i am grateful for any help you can provide !

0

3 Answers 3

3

Something like this?

function myjsoncallback(obj) {
  var result = [];

  for (var key in obj) {
    result.push(obj[key]);
  }

  // result is now an array of the input object's values.
}

If you're using jQuery 1.6+, jQuery's $.map() function now works against objects and simplifies the syntax a bit more (though it's doing the same thing under the hood):

function myjsoncallback(obj) {
  var result = $.map(obj, function(value, key) {
    return value;
  });
}

To use this with a jQuery $.getJSON call to a service that properly supports JSONP, you can do something like this:

$.getJSON('http://some.api.com/x/y/x?callback=?', function(response) {
  var values = $.map(response, function(value, key) {
    return value;
  });

  // Do something with "values" here.
});

When you specify callback=? instead of hard coding your own callback function name, jQuery will automatically substitute a uniquely named one for each request (that way you don't have to worry about keeping straight which callback execution matches which request if you end up having more than one simultaneous request). Since it does that for you, you can just pass in an anonymous function for the callback parameter and not worry about setting up a standalone function at all.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the jQuery solution would i attach this within my success callback $.getJSON or outside of the call ?
@Xavier: Edited my answer with an example of using it with $.getJSON.
0
function myjsoncallback(data) {
  var output = [];
  for (var x in data) {
    output.push(data[x]);
  }
  return output;
}

myjsoncallback({"h1": "cmPanel", "h2" : "cmAuto", "h3": 0});

Comments

0
var ar = [];
for (var prop in your_json) {
      ar.push(your_son[prop]);
   }

I hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.