0

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?

0

4 Answers 4

5

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.

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

3 Comments

What if I am using JQuery. Is it getJson()?
Yes you should use the getJSON() method: docs.jquery.com/Ajax/jQuery.getJSON
...and you need another single quote. (:
1

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.

2 Comments

Source is trusted its my own server, but I prefer to use JQuery. Is it the getJSon() function?
You need brackets around the response
0

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

var myObj = JSON.parse(respsonse);

Comments

0

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

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.