在PHP json_decode()中检测到错误的json数据? [英] Detect bad json data in PHP json_decode()?

查看:786
本文介绍了在PHP json_decode()中检测到错误的json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过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:\server\www\myserver.dev\public_html\rivrUI\public_home\index.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 :

  • 它返回数据,或者在出现错误时返回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.


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


To solve the warning problem, a solution would be to use the @ operator (I don't often recommend using it, as it makes debuging a lot more harder... But here, there is not much of a choice) :

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

然后,您必须测试$data是否为null,并且,为避免json_decode在JSON字符串中为null返回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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆