我需要一个非常非常快的方法来检查字符串是否为JSON。我觉得这不是最好的方式:

function isJson($string) {
    return ((is_string($string) &&
            (is_object(json_decode($string)) ||
            is_array(json_decode($string))))) ? true : false;
}

有没有表演爱好者想改进这种方法?


当前回答

//Tested thoroughly, Should do the job:
public static function is_json(string $json):bool
{
    json_decode($json);
    if (json_last_error() === JSON_ERROR_NONE) {
        return true;
    }
    return false;
}

其他回答

2023年的今天,时代的回答:

虽然PHP 8.3仍在开发中,将提供新的内存效率高的json_validate()函数,但由于神奇的Symfony Polyfill组件,您可以在较旧的PHP版本(7.1和更新的版本)中使用它。

只需将以下包添加到您的项目:

composer require symfony/polyfill-php83

并在应用程序中使用它:

if (json_validate($data)) {
  // do sometihng
}

由于这种方法,您可以在旧的应用程序中使用新的PHP特性,并且在将来无需任何代码更改就可以迁移到PHP 8.3,因为当内置函数可用时,您的代码将自动使用它。

function isJson($string) {
   json_decode($string);
   return json_last_error() === JSON_ERROR_NONE;
}
function is_json($str){ 
    return json_decode($str) != null;
}

当检测到非法编码时,http://tr.php.net/manual/en/function.json-decode.php返回值为空。

我试过其中的一些方法,但没有一种对我有效。我尝试了这么简单的事情:

$isJson = json_decode($myJSON);

if ($isJson instanceof \stdClass || is_array($isJson)) {
   echo("it's JSON confirmed");
} else {
   echo("nope");
}

我认为这是一个很好的解决方案,因为JSON解码没有第二个参数给出一个对象。

编辑:如果知道输入内容,就可以根据需要调整代码。在我的情况下,我知道我有一个Json以“{”开始,所以我不需要检查它是否是一个数组。

//Tested thoroughly, Should do the job:
public static function is_json(string $json):bool
{
    json_decode($json);
    if (json_last_error() === JSON_ERROR_NONE) {
        return true;
    }
    return false;
}