Page 1 of 1

Issues with json_decode

Posted: Mon Jul 21, 2008 12:48 pm
by rubinsta
Hi,

I'm using PHP 5.2.5 on Debian 'etch' and I'm having trouble decoding a JSON response with json_decode().

Here's the code:

Code: Select all

 
<?php
$json = {
    "status": "ok", 
    "result": {
        "publishers": [
            "Jewish Press Pub. Co."
        ], 
        "subtitle": "a complete lexicon and work of reference in all departments of knowledge.  Prepared under the editorship of Paul Abelson.", 
        "key": "\/b\/OL7168569M", 
        "title": "English-Yiddish encyclopedic dictionary", 
        "coverimage": "\/static\/files\/\/686\/OL7168569M_coverimage_1216390649614686.jpg", 
        "ocaid": "englishyiddishen02abeluoft", 
        "lc_classifications": [
            "PJ5117 A2"
        ], 
        "latest_revision": 4, 
        "publish_country": "|||", 
        "last_modified": "2008-07-18T16:50:41.869538", 
        "authors": [
            {
                "key": "\/a\/OL2536900A"
            }
        ], 
        "publish_date": "1915", 
        "publish_places": [
            "New York"
        ], 
        "type": {
            "key": "\/type\/edition"
        }, 
        "subjects": [
            "English language -- Dictionaries -- Yiddish"
        ], 
        "revision": 4
    }
}
 
$obj = json_decode($json);
print $obj->{'result'};
?>
 
When I execute the script I get the following error:

Code: Select all

Catchable fatal error:  Object of class stdClass could not be converted to string
I'm by no means an expert in either JSON or PHP for that matter but the JSON looks fine to me. Is there something obvious I'm missing? The JSON is from the OpenLibrary API and I've seen applications that successfully decode the JSON results from this API with PHP. Any help would be very appreciated...

Thanks!

Re: Issues with json_decode

Posted: Mon Jul 21, 2008 1:11 pm
by Christopher
'result' is an object, try:

Code: Select all

$obj = json_decode($json);
echo $obj->result->subtitle;
// or
print_r($obj->result);

Re: Issues with json_decode

Posted: Mon Jul 21, 2008 1:26 pm
by rubinsta
Thanks for such a quick reply! That did the trick. So I can use the $obj->{'foo'} syntax to put the corresponding JSON object into a variable but I need to print_r to get the data out in human readable form?

Thanks again!

Re: Issues with json_decode

Posted: Mon Jul 21, 2008 1:38 pm
by Christopher
echo()/print() only work with scalars. If you have an array or object (like $obj->result) then you need to directly reference scalar elements/properties of the variable. Or use some function that will convert it to a scalar, such as print_r(), implode(), etc.