views:

140

answers:

4

Hello all,

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?

+1  A: 

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.

brownstone
Source is trusted its my own server, but I prefer to use JQuery. Is it the getJSon() function?
Abs
You need brackets around the response
Greg
+5  A: 

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.

Greg
What if I am using JQuery. Is it getJson()?
Abs
Yes you should use the getJSON() method: http://docs.jquery.com/Ajax/jQuery.getJSON
Greg
...and you need another single quote. (:
peirix
So I do... did..
Greg
A: 

You can also download the official JSON parser for javascript, which would let you do:

var myObj = JSON.parse(respsonse);
peirix
A: 

Crockford doesn't recommend the eval() function.

http://json.org/js.html

You could use his json parse/stringify function instead

http://json.org/json2.js

Steve Claridge