Centurion
Centurion

Reputation: 14304

How to return null instead of empty array or empty object?

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

Answers (2)

nvanesch
nvanesch

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

pythonian29033
pythonian29033

Reputation: 5207

can't you do this?:

print ($json == '[]') ? null : $json;

Upvotes: 0

Related Questions