gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:46:44 29 4
gpt4 key购买 nike

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

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

如果 $_POST 等于:

'{ bar: "baz" }'

然后 json_decode 处理错误并吐出“bad json data!”;但是,如果我将 $_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 数据,还是有其他一些不错的方法来检测这个?

最佳答案

这里有几件事是关于 json_decode :

  • 返回数据,如果出错则返回null
  • 在没有错误的情况下也可以返回null:当JSON字符串包含null
  • 它会在有警告的地方发出警告 - 您想要让警告消失。


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

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

然后您必须测试 $data 是否为 null -- 并且,为了避免 json_decode 返回 的情况>null 表示 JSON 字符串中的 null,您可以查看 json_last_error ,其中(引用):

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


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

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

关于php - 在 PHP json_decode() 中检测错误的 json 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2348152/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com