php json_encode doesn't result in real object / make array string into real object / turn php array into json

StackOverflow https://stackoverflow.com/questions/4293295

Question

Here is my PHP code, it's getting a listing of collections from mongodb

$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
    $result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );

I do console.log in the callback and this is what I see.

["fruits", "dogs", "cars", "countries"]

The problem is that this is a string, not an array. I need to iterate through these values. How an I make this into a real object or get php to give me json rather than php array so I can use parseJSON on it.

Thanks.

js:

$.post('/ajax-database.php', function (data) {
    console.log($.parseJSON(data));
    $.each(data, function (key, value) {
        console.log(value);
    });
});
Was it helpful?

Solution

I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.

  1. add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text

  2. Add a forth parameter to your $.post,

$.post('/ajax-database.php', function (data) {
    console.log($.parseJSON(data));
    $.each(data, function (key, value) {
        console.log(value);
    });
}, "json");

that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.

OTHER TIPS

JSON is strings. If you want to be able to iterate over it then you need to decode it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top