且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 PHP json_decode() 中检测错误的 json 数据?

更新时间:2023-12-04 14:23:56

这里有一些关于 json_decode :

Here are a couple of things about json_decode :

  • 返回数据,或者null出现错误时
  • 它也可以在没有错误时返回null:当JSON字符串包含null
  • 它会在有警告的地方发出警告 - 您想让警告消失.
  • it returns the data, or null when there is an error
  • it can also return null when there is no error : when the JSON string contains null
  • it raises a warning where there is a warning -- warning that you want to make disappear.


要解决警告问题,解决方案是使用 @ 运算符 (我不经常推荐使用它,因为它使调试变得更加困难......但在这里,没有太多选择) :

$_POST = array(
    'bad data'
);
$data = @json_decode($_POST);

然后您必须测试 $data 是否为 null -- 并且避免出现 json_decode 返回 null 对于 JSON 字符串中的 null,您可以检查 json_last_error,其中 (引用) :

You'd then have to test if $data is null -- and, to avoid the case in which json_decode returns null for null in the JSON string, you could check json_last_error, which (quoting) :

返回最后一个错误(如果有)由上次 JSON 解析发生.

Returns the last error (if any) occurred by last JSON parsing.


这意味着您必须使用如下代码:


Which means you'd have to use some code like the following :

if ($data === null
    && json_last_error() !== JSON_ERROR_NONE) {
    echo "incorrect data";
}