有没有人知道一个健壮(且防弹)的 PHP is_JSON 函数片段?我(显然)有这样一种情况,需要知道一个字符串是否为 JSON。
或许可以通过 JSONLint 的请求/响应来运行它,但这似乎有点过度杀手。
或许可以通过 JSONLint 的请求/响应来运行它,但这似乎有点过度杀手。
json_decode
PHP 函数,json_last_error
将返回最后一个错误 (例如,当您的字符串不是JSON格式时,它会返回JSON_ERROR_SYNTAX
)。json_decode
无论如何都会返回 null
。// PHP >= 5.6
function is_JSON(...$args) {
json_decode(...$args);
return (json_last_error()===JSON_ERROR_NONE);
}
使用 PHP >= 5.3
// PHP >= 5.3
function is_JSON() {
call_user_func_array('json_decode',func_get_args());
return (json_last_error()===JSON_ERROR_NONE);
}
使用示例:
$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
echo "Valid JSON string";
} else {
$error = json_last_error_msg();
echo "Not valid JSON string ($error)";
}
PHP致命错误:func_get_args():无法用作函数参数
。我将在函数定义中直接定义该参数。 - Kellen Stuart使用json_decode
怎么样?如果给定的字符串不是有效的JSON编码数据,它应该返回null
。
请参阅手册页面上的示例3:
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
如果 json_decode()
和 json_last_error()
对你没有用,你是在寻找一种只能说“这看起来像JSON”还是实际验证它的方法?json_decode()
将是 PHP 中有效验证它的唯一方法。
这是最好和高效的方法。
function isJson($string) {
return (json_decode($string) == null) ? false : true;
}
$this->post_data = json_decode( stripslashes( $post_data ) ); 如果 $this->post_data 为 NULL,那么: { die( '{"status":false,"msg":"post_data 参数必须是有效的 JSON"}' ); }
json_validate() 将在 PHP 8.3 中推出