如何确定一个字符串是否是有效的 JSON?

47
有没有人知道一个健壮(且防弹)的 PHP is_JSON 函数片段?我(显然)有这样一种情况,需要知道一个字符串是否为 JSON。
或许可以通过 JSONLint 的请求/响应来运行它,但这似乎有点过度杀手。

1
射击;我有一个防弹的解决方案,但是它不够健壮,所以我不得不放弃它 :P - user212218
7个回答

71

3
没错,我是个白痴。这很明显,但我刚好忽略了它。我可以把这个问题解决掉。谢谢。 - Spot
在大多数情况下,这是一种可靠的解决方案,但要注意。json_decode也可以解析数字字符串。字符串中的电话号码将被转换为整数。但是,这并不是在每个服务器上都会发生的。在我的Windows机器上,我得到的是整数,在Linux开发系统上,我得到的是false。我认为这取决于您的PHP安装和配置。 - StoryTeller
正如StoryTeller所提到的那样 - json_decode("51232")的计算结果为51232,因此在所有情况下可能都不是有用的。 - Paul Preibisch

20
对于我的项目,我使用这个函数(请阅读json_decode()文档上的“Note”)。
通过传递与json_decode()相同的参数,您可以检测特定应用程序“错误”(例如深度错误)。
PHP版本需不低于5.6。
// 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)";
}

嗨@LiranH,原帖请求一个'is_JSON'函数,因此我不能在函数内假设json_decode刚刚对所请求的字符串执行过。在这种情况下,您的函数将被命名为'is_last_json_decoded_string_a_JSON_string'。 - cgaldiolo
这很公平 @cgaldiolo - Liran H
尝试了您的Php < 5.6答案,但出现了这个错误:PHP致命错误:func_get_args():无法用作函数参数。我将在函数定义中直接定义该参数。 - Kellen Stuart
嗨@KolobCanyon,这是因为您正在使用PHP <5.3。我的解决方案仅适用于PHP> = 5.3,因为该版本开始提供函数json_last_error()。我正在更新答案,谢谢。 - cgaldiolo
@KolobCanyon 这是我用来检查简单代码在不同版本下运行情况的工具:https://3v4l.org/ - cgaldiolo
显示剩余2条评论

17

使用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

"null" 是有效的 JSON,但它也会返回 null。只是挑剔而已! - wordbug

4

如果 json_decode()json_last_error() 对你没有用,你是在寻找一种只能说“这看起来像JSON”还是实际验证它的方法?json_decode() 将是 PHP 中有效验证它的唯一方法。


4

这是最好和高效的方法。

function isJson($string) {
    return (json_decode($string) == null) ? false : true;
}

3
$this->post_data = json_decode( stripslashes( $post_data ) );
如果 $this->post_data 为 NULL,那么:
{
   die( '{"status":false,"msg":"post_data 参数必须是有效的 JSON"}' );
}

1

json_validate() 将在 PHP 8.3 中推出


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接