0

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?

1
  • 1
    one simple if condition doesn't seem easy enough for you? Commented Jul 23, 2013 at 14:05

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

can't you do this?:

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

1 Comment

Webservices contain quite a big nested data structure, so a lot of manual checks would be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.