我需要一个非常非常快的方法来检查字符串是否为JSON。我觉得这不是最好的方式:
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
有没有表演爱好者想改进这种方法?
我需要一个非常非常快的方法来检查字符串是否为JSON。我觉得这不是最好的方式:
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
有没有表演爱好者想改进这种方法?
当前回答
在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 json_decode($str) != null;
}
当检测到非法编码时,http://tr.php.net/manual/en/function.json-decode.php返回值为空。
我们需要检查传递的string是否不是数字,因为在这种情况下json_decode不会引发错误。
function isJson($str) {
$result = false;
if (!preg_match("/^\d+$/", trim($str))) {
json_decode($str);
$result = (json_last_error() == JSON_ERROR_NONE);
}
return $result;
}
另一种简单的方法
function is_json($str)
{
return is_array(json_decode($str,true));
}
function isJson($string) {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
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,因为当内置函数可用时,您的代码将自动使用它。