Hi,
A website returns the following JSON response, how would I consume it (in javascript)?
[{"ID1":9996,"ID2":22}]
Is JSON simply returning an array?
-
We use:
function evalResponse(response) { var xyz123 = null; eval("xyz123 = " + response); return xyz123; }An alternative method is to simply use:
var myObj = eval(response);Basically, you have to call
eval()on the response to create a javascript object. This is because the response itself is just a string when you get it back from your AJAX call. After youevalit, you have an object that you can manipulate.function myCallback(response) { var myObj = evalResponse(response); alert(myObj.ID1); }You could use a javascript library to handle this for you. Or, you could try to parse the string yourself.
eval()has it's own problems, but it works.Joel Coehoorn : upvote for the trick using an extra assignment to stop some security vulnerabilities: if it's not assignable, the eval will just fail.EndangeredMassa : Thanks. It can still be worked around, but it's an extra level for a malicious user to worry about. -
Here's how you get to your data:
<script type="text/javascript" > var something = [{"ID1":9996,"ID2":22}] alert(something[0].ID1) </script>EndangeredMassa : That doesn't include the response. -
It looks like an array with a single object holding two properties. I'd much prefer to see the same data structured like this:
{"ID":[9996,22]}
Then you have a single object holding an array with two elements, which seems to be a better fit for the data presented. Then using Endangered's
evalResponse()code you could use it like this:var responseObj = evalResponse(response); // responseObj.ID[0] would be 9996, responseObj.ID[1] would be 22 -
The JSON you posted represents an array containing one object, which has attributes ID1 and ID2 (initialized to the respective values after the colon).
To convert the string to a javascript object, pass it to eval, like this:
var obj = eval('[{"ID1":9996,"ID2":22}]');However, this method will fail if you only have a single object instead of an array, so it is safer to wrap it in parenthesis:
var obj = eval('(' + jsonResponse + ')'); -
If you use http://www.JSON.org/json2.js you can use it's method JSON.parse to retrieve the json string as an object (without the use of eval (which is considered evil)), so in this case you would use:
var nwObj = JSON.parse('[{"ID1":9996,"ID2":22}]'); alert(nwObj.ID1); //=> 9996 -
I think the other answers might not answer your question, maybe you're looking for a way to use that "array of 1 object". Maybe this can help:
var arr = [{"ID1":9996,"ID2":22}]; var obj = arr[0]; var id1 = obj.ID1; var id2 = obj.ID2;
0 comments:
Post a Comment