我需要一个非常非常快的方法来检查字符串是否为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($string) {
return is_null(json_decode($string));
}
其他回答
function isJson($string) {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
更新: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 isJson($string) {
$decoded = json_decode($string); // decode our JSON string
if ( !is_object($decoded) && !is_array($decoded) ) {
/*
If our string doesn't produce an object or array
it's invalid, so we should return false
*/
return false;
}
/*
If the following line resolves to true, then there was
no error and our JSON is valid, so we return true.
Otherwise it isn't, so we return false.
*/
return (json_last_error() == JSON_ERROR_NONE);
}
if ( isJson($someJsonString) ) {
echo "valid JSON";
} else {
echo "not valid JSON";
}
如其他答案所示,json_last_error()返回来自上一次json_decode()的任何错误。然而,在一些边缘用例中,仅使用这个功能还不够全面。例如,如果你json_decode()一个整数(例如:123),或者一个没有空格或其他字符的数字字符串(例如:“123”),json_last_error()函数将不会捕获错误。
为了解决这个问题,我添加了一个额外的步骤,以确保json_decode()的结果是一个对象或数组。如果不是,则返回false。
要查看具体操作,请查看以下两个示例:
只使用json_last_error()检查 首先检查对象/数组
我使用的最简单和最快的方法是跟随;
$json_array = json_decode( $raw_json , true );
if( $json_array == NULL ) //check if it was invalid json string
die ('Invalid'); // Invalid JSON error
// you can execute some else condition over here in case of valid JSON
这是因为如果输入的字符串不是json或无效json, json_decode()将返回NULL。
验证JSON的简单函数
如果您必须在多个地方验证JSON,您总是可以使用下面的函数。
function is_valid_json( $raw_json ){
return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it.
}
在上面的函数中,如果它是一个有效的JSON,则返回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 )