我需要一种非常非常快速的检查字符串是否为JSON的方法。我觉得这不是最好的方法:
function isJson($string) {
return ((is_string($string) &&
(is_ (json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
php爱好者有什么最佳的方法吗?
json_last_error函数返回JSON编码和解码期间发生的最后一个错误。因此,检查有效JSON的最快方法是
// decode the JSON data
// set second parameter boolean TRUE for associative array output.
$result = json_decode($json);
if (json_last_error() === JSON_ERROR_NONE) {
// JSON is valid
}
// OR this is equivalent
if (json_last_error() === 0) {
// JSON is valid
}
请注意,json_last_error仅在PHP> = 5.3.0中受支持。
在开发期间知道确切的错误总是很好的。这是完整的程序,以检查基于PHP文档的确切错误。
function json_validate($string)
{
// decode the JSON data
$result = json_decode($string);
// switch and check possible JSON errors
switch (json_last_error()) {
case JSON_ERROR_NONE:
$error = \'\'; // JSON is valid // No error has occurred
break;
case JSON_ERROR_DEPTH:
$error = \'The maximum stack depth has been exceeded.\';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = \'Invalid or malformed JSON.\';
break;
case JSON_ERROR_CTRL_CHAR:
$error = \'Control character error, possibly incorrectly encoded.\';
break;
case JSON_ERROR_SYNTAX:
$error = \'Syntax error, malformed JSON.\';
break;
// PHP >= 5.3.3
case JSON_ERROR_UTF8:
$error = \'Malformed UTF-8 characters, possibly incorrectly encoded.\';
break;
// PHP >= 5.5.0
case JSON_ERROR_RECURSION:
$error = \'One or more recursive references in the value to be encoded.\';
break;
// PHP >= 5.5.0
case JSON_ERROR_INF_OR_NAN:
$error = \'One or more NAN or INF values in the value to be encoded.\';
break;
case JSON_ERROR_UNSUPPORTED_TYPE:
$error = \'A value of a type that cannot be encoded was given.\';
break;
default:
$error = \'Unknown JSON error occured.\';
break;
}
if ($error !== \'\') {
// throw the Exception or exit // or whatever :)
exit($error);
}
// everything is OK
return $result;
}
使用有效的JSON INPUT进行测试
$json = \'[{\"user_id\":13,\"username\":\"stack\"},{\"user_id\":14,\"username\":\"over\"}]\';
$output = json_validate($json);
print_r($output);
有效的输出
Array
(
[0] => stdClass
(
[user_id] => 13
[username] => stack
)
[1] => stdClass
(
[user_id] => 14
[username] => over
)
)
使用无效的JSON进行测试
$json = \'{background-color:yellow;color:#000;padding:10px;width:650px;}\';
$output = json_validate($json);
print_r($output);
无效的输出
Syntax error, malformed JSON.
额外注意事项(PHP> = 5.2 && PHP <5.3.0)
由于json_last_errorPHP 5.2不支持,您可以检查编码或解码是否返回布尔值FALSE。这是一个例子
// decode the JSON data
$result = json_decode($json);
if ($result === FALSE) {
// JSON is invalid
}
希望这有用。快乐的码农!
继续阅读与本文标签相同的文章
上一篇 :
PHP将HTTP头设置为UTF-8
-
广汽新能源Aion LX上市:售价24.96万元起,综合续航650公里
2026-05-15栏目: 教程
-
能打败复读机的,只有禁止套娃了
2026-05-15栏目: 教程
-
联通卡有信号但是不显示4G网络该怎么办?
2026-05-15栏目: 教程
-
python 换行技巧
2026-05-15栏目: 教程
-
小孩拉粑粑,可穿戴设备实时监控,5G对C端的改变也是颠覆性的
2026-05-15栏目: 教程
