【问题标题】:How to return null instead of empty array or empty object?如何返回 null 而不是空数组或空对象?
【发布时间】:2013-07-22 15:47:21
【问题描述】:

默认情况下,php json_encode() 为空数组返回“[]”空括号。此外,还可以更改为返回“{}”括号:

<?php

  $result = array();
  $json = json_encode($result, JSON_FORCE_OBJECT);
  print($json);

如果数组为空,则需要修复 Web 服务以返回 null 而不是空括号。有没有简单又标准的方法?

【问题讨论】:

  • 一个简单的if 条件对您来说似乎还不够简单?

标签: php json


【解决方案1】:

我知道你会有很深的嵌套结构,并且你想用 null 替换空叶子。

如果是这种情况,您可以简单地查找和替换。

$result = array("test" => array("Foo"=> new stdClass()), "testy" => array());
$json = json_encode($result);
$strippedJson = str_replace(array('[]', '{}'), 'null', $json);

会给这个json:

{"test":{"Foo":null},"testy":null}

请注意,它会替换空叶子,但不会替换仅包含空叶子的分支。

【讨论】:

    【解决方案2】:

    你不能这样做吗?:

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

    【讨论】:

    • Web 服务包含相当大的嵌套数据结构,因此需要进行大量手动检查。
    猜你喜欢
    • 2019-05-14
    • 2018-10-11
    • 1970-01-01
    • 2019-06-05
    • 2021-07-30
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多