用php的json_decode()检测json数据是否合法

Pascal MARTIN


要实现类似下面的功能

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


如果json格式不合法,给出提示,退出。但上面的代码可能给有下面的提示:

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!


更好的解决方法是:

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

可能的情况是:
当格式是错误的,返回NULL,正确的话返回数据给$data。
当没有错误的情况下,也可能返回NULL,当JSON字符串包含null。
产生一个警告,用@抑制警告信息的输出。(实际上我不建议经常使用它,因为它使调试运行了很多困难......但在这里,没有多少选择的余地)

然后,你有必要测试,如果$data为空的情况,json_decode返回的信息,你可以检查json_last_error。
  JSON解析发生返回最后一个错误(如果有的话)

这意味着你不得不使用下面的代码:

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

京ICP备14008139号-1