如何判断一个字符串是否是有效的JSON?

问题描述 投票:0回答:8

有人知道 PHP 的强大(且防弹) is_JSON 函数片段吗?我(显然)有一种情况,我需要知道字符串是否是 JSON。

嗯,也许可以通过 JSONLint 请求/响应来运行它,但这似乎有点矫枉过正。

php json validation code-snippets jsonlint
8个回答
71
投票

如果您使用内置的

json_decode
PHP 函数,
json_last_error
返回最后一个错误(例如,当您的字符串不是 JSON 时,
JSON_ERROR_SYNTAX
)。

通常

json_decode
无论如何都会返回
null


21
投票

对于我的项目,我使用此函数(请阅读 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)";
}

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

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 ) );
  if( $this->post_data === NULL )
   {
   die( '{"status":false,"msg":"post_data 参数必须是有效的 JSON"}' );
   }

1
投票

json_validate() 将在 PHP 8.3 中上线


0
投票

终于!从 PHP 8.3 开始,可以使用新的 json_validate() 函数:

$fixtures = [
    // Not valid
    'foo',
    '{foo: bar}',
    "'{'foo': 'bar'}",
    '{...}',

    // Valid
    '"foo"',
    '1',
    '{"foo": "bar"}',
];

foreach ($fixtures as $string) {
    if (json_validate($string)) {
        echo sprintf('YES, >%s< is a valid JSON string', $string).PHP_EOL;
        echo 'decoded: '. var_export(json_decode($string), true).PHP_EOL;
    } else {
        echo sprintf('NO, >%s< is NOT a valid JSON string: %s', $string, json_last_error_msg()). PHP_EOL;
    }
}

此函数仅接受字符串作为第一个参数:此片段的输出

© www.soinside.com 2019 - 2024. All rights reserved.