I\'m passing a JSON-encoded string to json_decode()
and am expecting its output to be an object type, but am getting a string type instead. How can I return an
The function json_encode
is used to encode a native PHP object or array in JSON format.
For example, $json = json_encode($arr)
where $arr
is
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
);
would return the string $json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'
. At this point, you do not need to encode it again with json_encode
!
To obtain your array back, simply do json_decode($json, true)
.
If you omit the true
from the call to json_decode
you'll obtain an instance of stdClass
instead, with the various properties specified in the JSON string.
For more references, see:
http://www.php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.json-decode.php
Instead of writing on the JSON array, try putting it into a PHP array first.
<?php
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5
);
//Then json_encode()
$json = json_encode($array);
echo $json;
die;
?>
In you case, you are using ajax. So when you get a success, you can do this:
$.ajax({
url: 'example.com',
data: {
},
success: function(data) {
console.log(data);
}
});
Where after data inside console.log() can add the json var like data.a, data.b...
Also, with the string you providedm you do not need to json_encode since it is alrady in json format
var_dump(json_decode($json, true));
http://hk.php.net/manual/en/function.json-decode.php