小编典典

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

json

通过json_decode()解析时,我正在尝试处理错误的json数据。我正在使用以下脚本:

if(!json_decode($_POST)) {
  echo "bad json data!";
  exit;
}

如果$ _POST等于:

'{ bar: "baz" }'

然后,json_decode会正确处理错误并吐出“错误的json数据!”;但是,如果我将$ _POST设置为“无效数据”之类的东西,它将给我:

Warning: json_decode() expects parameter 1 to be string, array given in C:\server\www\myserver.dev\public_html\rivrUI\public_home\index.php  on line 6
bad json data!

我是否需要编写自定义脚本来检测有效的json数据,还是有其他一些漂亮的方法来检测到此数据?


阅读 207

收藏
2020-07-27

共1个答案

小编典典

以下是有关以下几点的信息json_decode

  • 它返回数据,或者null出现错误时
  • 它也可以null在没有错误的情况下返回:当JSON字符串包含null
  • 它会在有警告的地方发出警告-您要使其消失的警告。

为了解决警告问题,一种解决方案是使用@运算符
(我不经常建议使用它,因为它会使调试更加困难…但是在这里,没有太多选择)

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

然后,您必须测试是否$datanull-,并避免在JSON字符串中json_decode返回nullfor
的情况null,您可以检查json_last_error,which (引用)

返回上一次JSON解析发生的最后错误(如果有)。

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

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