我需要一个非常非常快的方法来检查字符串是否为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;
}
有没有表演爱好者想改进这种方法?
当前回答
应该是这样的:
function isJson($string)
{
// 1. Speed up the checking & prevent exception throw when non string is passed
if (is_numeric($string) ||
!is_string($string) ||
!$string) {
return false;
}
$cleaned_str = trim($string);
if (!$cleaned_str || !in_array($cleaned_str[0], ['{', '['])) {
return false;
}
// 2. Actual checking
$str = json_decode($string);
return (json_last_error() == JSON_ERROR_NONE) && $str && $str != $string;
}
单元测试
public function testIsJson()
{
$non_json_values = [
"12",
0,
1,
12,
-1,
'',
null,
0.1,
'.',
"''",
true,
false,
[],
'""',
'[]',
' {',
' [',
];
$json_values = [
'{}',
'{"foo": "bar"}',
'[{}]',
' {}',
' {} '
];
foreach ($non_json_values as $non_json_value) {
$is_json = isJson($non_json_value);
$this->assertFalse($is_json);
}
foreach ($json_values as $json_value) {
$is_json = isJson($json_value);
$this->assertTrue($is_json);
}
}
其他回答
function isJson($string) {
$obj = json_decode($string);
return json_last_error() === JSON_ERROR_NONE && gettype($obj ) == "object";
}
这是有效的,对于数字不返回true
新的更新
如果JSON很长并且你不需要使用$obj,上面的解决方案就没有很好的性能
如果你只是想检查一下,最好使用下面的函数
function isJson($string) {
if(is_numeric($string)) return false;
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
简单的方法是检查json结果..
$result = @json_decode($json,true);
if (is_array($result)) {
echo 'JSON is valid';
}else{
echo 'JSON is not valid';
}
对亨里克的回答做一个简单的修改,以触及最需要的可能性。
(包括“{}和[]”)
function isValidJson($string) {
json_decode($string);
if(json_last_error() == JSON_ERROR_NONE) {
if( $string[0] == "{" || $string[0] == "[" ) {
$first = $string [0];
if( substr($string, -1) == "}" || substr($string, -1) == "]" ) {
$last = substr($string, -1);
if($first == "{" && $last == "}"){
return true;
}
if($first == "[" && $last == "]"){
return true;
}
return false;
}
return false;
}
return false;
}
return false;
}
你真正需要做的就是…
if (is_object(json_decode($MyJSONArray)))
{
... do something ...
}
这个请求甚至不需要一个单独的函数。只需将is_object包装在json_decode周围,然后继续。似乎这个解决方案让人们花了太多心思。
如果有本地文件站。Json无效,缺失,或超过一个月,做一些事情。
if (!is_array(json_decode(@file_get_contents("stations.json"))) || time() > filemtime("stations.json") + (60*60*24*31)){
// The json file is invalid, missing, or is more than 1 month old
// Get a fresh version
} else {
// Up to date
}