在 PHP json_decode() 中检测错误的 json 数据? [英] Detect bad json data in PHP json_decode()?
问题描述
我试图在通过 json_decode() 解析时处理错误的 json 数据.我正在使用以下脚本:
I'm trying handle bad json data when parsed through json_decode(). I'm using the following script:
if(!json_decode($_POST)) {
echo "bad json data!";
exit;
}
如果 $_POST 等于:
If $_POST equals:
'{ bar: "baz" }'
然后 json_decode 会很好地处理错误并吐出错误的 json 数据!";但是,如果我将 $_POST 设置为无效数据"之类的内容,它会给我:
Then json_decode handles the error fine and spits out "bad json data!"; However, if I set $_POST to something like "invalid data", it gives me:
Warning: json_decode() expects parameter 1 to be string, array given in C:serverwwwmyserver.devpublic_html
ivrUIpublic_homeindex.php on line 6
bad json data!
我是否需要编写自定义脚本来检测有效的 json 数据,或者是否有其他一些不错的方法来检测?
Do I need to write a custom script to detect valid json data, or is there some other nifty way to detect this?
推荐答案
这里有一些关于 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 containsnull
- 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";
}
这篇关于在 PHP json_decode() 中检测错误的 json 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!