Reputation: 14304
By default php json_encode() returns "[]" empty brackets for empty array. Also, it's possible to change to return "{}" brackets:
<?php
$result = array();
$json = json_encode($result, JSON_FORCE_OBJECT);
print($json);
The thing is need to fix web services to return null instead of empty brackets if array if empty. Is there any easy and standard way?
Upvotes: 0
Views: 1221
Reputation: 2600
I understand you would have deep nested structures and you want to replace empty leaves with null.
If that is the case you could simply find and replace.
$result = array("test" => array("Foo"=> new stdClass()), "testy" => array());
$json = json_encode($result);
$strippedJson = str_replace(array('[]', '{}'), 'null', $json);
Will give this json:
{"test":{"Foo":null},"testy":null}
Please note that it replaces empty leaves, but it does not replace branches only containing null leaves.
Upvotes: 2