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

Spo*_*pot 42 php validation json code-snippets jsonlint

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

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

Daf*_*aff 66

如果您正在使用内置的json_decodePHP函数,则json_last_error返回最后一个错误(例如,JSON_ERROR_SYNTAX当您的字符串不是JSON时).

无论如何通常会json_decode返回null.

  • 是的,我是个白痴.这是显而易见的,我只是错过了它.我可以把它包装成我需要的东西.谢谢. (3认同)

Pas*_*TIN 17

怎么样使用json_decode,这应该返回null给定的字符串是无效的JSON编码的数据?

请参见手册页上的示例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
Run Code Online (Sandbox Code Playgroud)


cga*_*olo 16

对于我的项目,我使用此函数(请阅读json_decode()文档中的" 注意 " ).

传递相同的参数,您将传递给json_decode(),您可以检测特定的应用程序"错误"(例如深度错误)

PHP> = 5.6

// PHP >= 5.6
function is_JSON(...$args) {
    json_decode(...$args);
    return (json_last_error()===JSON_ERROR_NONE);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
    echo "Valid JSON string";
} else {
    $error = json_last_error_msg();
    echo "Not valid JSON string ($error)";
}
Run Code Online (Sandbox Code Playgroud)