方法来检查响应在PHP中是否为JSON


Method to Check whether the Response is JSON in PHP?

我需要一个函数来检查PHP 中的输入响应是否为JSON

例如,我的JSON就是这个

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

您可以在其上使用json_decode(),然后检查json_last_error()。如果您有一个错误,那么它不是有效的JSON。

请记住,仅仅检查null是不够的。字符串null是有效的JSON(并且它是这样解码的)。

使用此

function check_whether_json($response){
    if(json_decode($response) != NULL){
        return TRUE;
    }else{
        return FALSE;
    }
}

像这样检查

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

现在检查开始

if(check_whether_json($json)){
// Proceed ur code...
}
$json_request = (json_decode($request) != NULL) ? true : false;

取自:PHP检查传入请求是否为JSON类型

这样行吗?

是的,你可以这样验证。

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    if($json) {
       $ob = json_decode($json);
       if($ob === null) {
           echo 'Invalid Json';
       } else {
          echo 'Valid Json';
       }
    }