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

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

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


当前回答

我不知道我的解决方案的性能或优雅性,但这就是我正在使用的:

if (preg_match('/^[\[\{]\"/', $string)) {
    $aJson = json_decode($string, true);
    if (!is_null($aJson)) {
       ... do stuff here ...
    }
}

因为我所有的JSON编码字符串都以{”开头,所以用RegEx进行测试就足够了。我对RegEx一点也不流利,所以可能有更好的方法来做到这一点。另外:strpos()可能更快。

我只是想贡献我的价值。

备注:刚刚将RegEx字符串更新为/^[\[\{]\"/,也可以找到JSON数组字符串。所以它现在在字符串的开头寻找["或{"。

其他回答

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

$isJson = json_decode($myJSON);

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

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

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

昨天,我在工作中遇到了类似的问题,我发现了这个问题。我的解决方案是以上几种方法的混合:

function is_JSON($string) {

    return is_null(json_decode($string));
}

在GuzzleHttp:

/**
 * Wrapper for json_decode that throws when an error occurs.
 *
 * @param string $json    JSON data to parse
 * @param bool $assoc     When true, returned objects will be converted
 *                        into associative arrays.
 * @param int    $depth   User specified recursion depth.
 * @param int    $options Bitmask of JSON decode options.
 *
 * @return mixed
 * @throws \InvalidArgumentException if the JSON cannot be decoded.
 * @link http://www.php.net/manual/en/function.json-decode.php
 */
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
    $data = \json_decode($json, $assoc, $depth, $options);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \InvalidArgumentException(
            'json_decode error: ' . json_last_error_msg());
    }

    return $data;
}

/**
 * Wrapper for JSON encoding that throws when an error occurs.
 *
 * @param mixed $value   The value being encoded
 * @param int    $options JSON encode option bitmask
 * @param int    $depth   Set the maximum depth. Must be greater than zero.
 *
 * @return string
 * @throws \InvalidArgumentException if the JSON cannot be encoded.
 * @link http://www.php.net/manual/en/function.json-encode.php
 */
function json_encode($value, $options = 0, $depth = 512)
{
    $json = \json_encode($value, $options, $depth);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \InvalidArgumentException(
            'json_encode error: ' . json_last_error_msg());
    }

    return $json;
}

另一种简单的方法

function is_json($str)
{
    return is_array(json_decode($str,true));
}

简单的方法是检查json结果..

$result = @json_decode($json,true);
    if (is_array($result)) {
        echo 'JSON is valid';
    }else{
        echo 'JSON is not valid';
    }