Jared
Jared

Reputation: 2096

How can I parse a JSON object containing a PHP array of objects?

I have created an AJAX function that is used with pagination links to load a new page of posts on the fly, and have everything working great except I can't figure out how to parse a JSON object like this one.

This is the style of PHP that is getting passed as JSON:

Array (
    [0] => stdClass Object (
        ['var1'] => val1
        ['var2'] => var2
    )
    [1] => stdClass Object (
        ['var1'] => val1
        ['var2'] => var2
    )
    [3] => stdClass Object (
        ['var1'] => val1
        ['var2'] => var2
    )
)

And is being passed to it with this:

$response = json_encode( array( 'success' => true, 'posts' => $new_posts ) );

Where $new_posts is the array I'm trying to parse.

Can anybody show me how I can access these variables and their values? Thanks.

Update: Here's the JSON string

I'm trying to access these from JavaScript.

Update 2: When I use var posts = JSON.parse( response.posts ); I get the following error in Google Chrome Javascript Console:

Uncaught SyntaxError: Unexpected end of input

Update 3: I just checked Firebug and it only seems to be returning this for the JSON response text:

{"success":true,"posts":[]}

Upvotes: 1

Views: 1960

Answers (3)

Abbas
Abbas

Reputation: 6886

Since you are using jQuery, the best approach would be to use the parseJSON method:

var respObj = jQuery.parseJSON(response);

Upvotes: 1

Matt Lo
Matt Lo

Reputation: 5731

I'm assuming you want to access via JavaScript since you have this in PHP. On your XHR success callback, insert the response in a JSON.parse(); and access everything as follows

var data = JSON.parse(recievedData); // newer browsers, optionally you can use jQuery or eval()
console.log(data); // test;
// loop through all data
for(var i=0;i<data.length;++i) {
   console.log(data[i].var1); // expects val1
   console.log(data[i].var2); // expects val2
}
//access one bit
console.log(data[0].var1);

jQuery response method (there are many ways to achieve this)

var data = jQuery.parseJSON(recievedData)

Upvotes: 2

timdev
timdev

Reputation: 62894

JSON is valid javascript, so the most straightforward solution (assuming you trust the source of the json 100%) is to simply eval() it.

var response = eval(the_json);

if (response.success){
    var posts = response.posts
}

If you're using a library like jQuery, there are built-in methods to more safely evaluate json strings.

Upvotes: 0

Related Questions