Tuesday, 16 February 2010

json_decode Fatal error: Cannot use object of type stdClass as array

You may receive the following error when encoding and decoding information using json in php

Fatal error: Cannot use object of type stdClass as array

When using json_decode, information is by default converted into an object. You need to use the function get_object_vars to convert the object into an array, like so;


$new_data = get_object_vars(json_decode($data));

print_r($new_data);

?>

1 comment:

Sheefeni Hauwanga said...

Thanks for the post. When I first got an object back instead of an associate array I had to trawl google hardcore for a solution. Beyond your method I found a few other ways of accessing the data inside as well.You can just grab 'em like normal object properties, $obj->var and if the property is an array you can use it's index like any other. Or, you can pass true or JSON_FORCE_OBJECT to the json_decode function (json_decode($encoded, true) or json_decode($encoded, JSON_FORCE_OBJECT)) and the function will return an associated array.