I'm reading JSON data with PHP and that data contains empty objects (like {}). So the problem is, I have to handle the case when object is empty in different manner but I can't find good enough way to do the check. empty(get_object_vars(object)) looks too scary and very inefficient. Is there good way to do the check?
2 Answers. Show activity on this post. $tmp = (array) $object; var_dump(empty($tmp));
Simple function to validate JSON. If you have to validate your JSON in multiple places, you can always use the following function. function is_valid_json( $raw_json ){ return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes!
Therefore you can use count() (if the object is Countable). Or by using get_object_vars() , e.g.
php $json = '{"hello": ["world"], "goodbye": []}'; $decoded = json_decode($json); print "Is hello empty? " . empty($decoded->{'hello'}); print "\n"; print "Is goodbye empty? " . empty($decoded->{'world'}); print "\n"; ?>
How many objects are you unserializing? Unless empty(get_object_vars($object)) or casting to array proves to be a major slowdown/bottleneck, I wouldn't worry about it – Greg's solution is just fine.
I'd suggest using the the $associative flag when decoding the JSON data, though: 
json_decode($data, true) This decodes JSON objects as plain old PHP arrays instead of as stdClass objects. Then you can check for empty objects using empty() and create objects of a user-defined class instead of using stdClass, which is probably a good idea in the long run.
You could cast it to an array (unfortunately you can't do this within a call to empty():
$x = (array)$obj; if (empty($x))     ... Or cast to an array and count():
if (count((array)$obj))     ... If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With