我需要一个非常非常快的方法来检查字符串是否为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 is_json($input) {
$input = trim($input);
if (substr($input,0,1)!='{' OR substr($input,-1,1)!='}')
return false;
return is_array(@json_decode($input, true));
}
其他回答
更新:json_validate()将在PHP 8.3中上线
FYI:
我正在研究一个RFC,在php中添加一个新函数,它能够验证—只验证json字符串,而不生成对象/数组。
为什么是只验证的函数?因为json_decode()在解析json-string时创建了一个数组/对象,这会影响正在使用的内存量;这意味着在验证json字符串时可以达到最大内存限制。
为了给你一个概念,检查这段代码performance_test_json_validate()_vs_json_decode():
在该测试中,我们可以看到新函数json_validate()使用0 MB来验证json-string,而json_decode()需要109 MB(因为它在解析时在内存中创建了一个数组/对象)。
这是目前正在进行的工作,但我发布这篇文章是因为我对你对它的看法很感兴趣(我的意思是,从技术角度来看,不是你认为值得拥有它)。
Github: https://github.com/php/php-src/pull/9399
RFC(工作进行中):https://wiki.php.net/rfc/json_validate
期待您的意见/支持。
提前谢谢你。
function is_json($input) {
$input = trim($input);
if (substr($input,0,1)!='{' OR substr($input,-1,1)!='}')
return false;
return is_array(@json_decode($input, true));
}
只需添加这个条件:
check if the type is string and then json decode <?php $subject = ['description' => '200 extra contacts','value' => '15','product_code' => 'OS_CONT12']; $subject = '{"description":"200 extra contacts","value":15,"product_code":"OS_CONT12"}'; if(gettype($subject) == 'string'){ $data = json_decode($subject, true); print_r($data); } else{ print_r("saurabh kasmble"); } ?> OUTPUT : Array ( [description] => 200 extra contacts [value] => 15 [product_code] => OS_CONT12 )
简单的方法是检查json结果..
$result = @json_decode($json,true);
if (is_array($result)) {
echo 'JSON is valid';
}else{
echo 'JSON is not valid';
}
之前我只是检查一个空值,这实际上是错误的。
$data = "ahad";
$r_data = json_decode($data);
if($r_data){//json_decode will return null, which is the behavior we expect
//success
}
上面的代码可以很好地处理字符串。然而,只要我提供号码,它就中断了。为例。
$data = "1213145";
$r_data = json_decode($data);
if($r_data){//json_decode will return 1213145, which is the behavior we don't expect
//success
}
要修复它,我所做的很简单。
$data = "ahad";
$r_data = json_decode($data);
if(($r_data != $data) && $r_data)
print "Json success";
else
print "Json error";