Reputation: 57966
I get a response form my server via AJAX with an array that is json_encode (php funciton). However, I am having difficulty parsing it.
I can do this:
alert(response);
But it just gives me a bunch of text like so:
[{"user_id":"Dev_V2_MEH_0910_M03_v03c_NEW_CODE_03"......"grouper_opae_algorithm":"nap_v42lp"}]
Please note, I cut out a lot. I have tried this:
alert(response[0].user_id);
That just gives me undefined.
What am I doing wrong?
Upvotes: 0
Views: 353
Reputation: 321824
You're getting it back as a string - you need to convert it into an object.
If you're using a library like jQuery or Prototype then there will be a built-in method to do this. Otherwise you can use eval:
object = eval('(' + response + ')');
This does open some security holes though - if a function was injected into the JSON it would be executed.
Upvotes: 5
Reputation: 11090
Crockford doesn't recommend the eval() function.
You could use his json parse/stringify function instead
Upvotes: 0
Reputation: 37771
You can also download the official JSON parser for javascript, which would let you do:
var myObj = JSON.parse(respsonse);
Upvotes: 0
Reputation: 5427
The most basic way to parse JSON is with the eval() command:
json = eval(response);
alert(json[0].user_id);
It's better to use libraries like Prototype or jQuery to help sanitize your JSON if the source is untrusted.
Upvotes: 1