techie_28
techie_28

Reputation: 2133

Json string to a js array

I have a set of result which i have converted to Json using php json_encode function now i want this result as an array in js but I am not getting an idea to do this.

My PHP array is like this :

Array
(
    [latestRating] => Array
        (
            [456] => Anonymous has rated xxx9
            [457] => Anonymous has rated xxxx8
            [458] => Anonymous has rated xxxx3.5
        )

    [latestUser] => Array
        (
            [242] => xxxxhas just signed up
            [243] => xxxxxhas just signed up
            [244] => xxxxxxhas just signed up
        )

)

When i do a php json_encode function on this i get following string

{"latestRating":{"456":"Anonymous has rated mermaidbl00d 9","457":"Anonymous has rated GeorgiaHallx 8","458":"Anonymous has rated smithjhon 3.5","459":"Anonymous has rated Emilyxo 8.5","460":"Anonymous has rated leona 10","461":"Anonymous has rated leona 10","462":"Anonymous has rated W0rthlessliar 8","463":"Anonymous has rated Yousamsuck 9","464":"Anonymous has rated Aimeeerobbb 9","465":"Anonymous has rated lauramillerx 10","466":"Anonymous has rated tomwaz 1","467":"Anonymous has rated W0rthlessliar 1","468":"Anonymous has rated W0rthlessliar 1","469":"Anonymous has rated W0rthlessliar 1","470":"Anonymous has rated W0rthlessliar 1"},"latestUser":{"242":"rhiwilliamsx has just signed up","243":"W0rthlessliar has just signed up","244":"rebeccaronan has just signed up"}}

I tried using JSON.stringify and then jQuery.makeArray also to create an array out of it. Then i tried eval('['+string+']') but none of them helped.

I am a newbie in Json couldnt find appropriate support as well.

Regards Himanshu Sharma.

Upvotes: 2

Views: 276

Answers (2)

Rob W
Rob W

Reputation: 349262

Use JSON.parse() instead of JSON.stringify.
The fist is JavaScript's equivalent to PHP's json_decode, the latter equivalent to json_encode.

Note: If you're using jQuery.ajax with dataType: 'json', then the parameter in the callback is already a decoded object.

In your code, the PHP "array" is not a JavaScript array, but an object.

Upvotes: 3

SeanCannon
SeanCannon

Reputation: 78046

It should already be ready to go if you're using json_encode(), if not, use JSON.parse(). You can also check the PHP headers when you're echoing the data to include:

header('Content-type: application/json');

If it's coming back from an ajax response, just reference the object like so:

success : function(data) {
    console.log(data.latestRating);
}

Upvotes: 2

Related Questions