任何人都不会知道的一个强大的(以及防弹)is_JSON功能段PHP?I(显然)有一种情况,我需要知道如果一串是JSON或没有。

嗯,也许是通过运行一个 JSONLint 请求/回应,但是那似乎有点过度破坏。

有帮助吗?

解决方案

如果您使用的是建立在 json_decode PHP function, json_last_error 返回的最后一个错误(例如 JSON_ERROR_SYNTAX 当你的串不JSON).

通常 json_decode 返回 null 无论如何。

其他提示

怎么样使用 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

对于我的项目,我在的注意“ #refsect1-function.json解码参数”的rel = “noreferrer”> json_decode()文档)。

传递相同的参数将传递给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)";
}

不与你json_decode()工作json_last_error()?您是否正在寻找只是说“这是否看起来像JSON”或实际验证它的方法? json_decode()将内PHP有效地验证它的唯一方式。

$this->post_data = json_decode( stripslashes( $post_data ) );
  if( $this->post_data === NULL )
   {
   die( '{"status":false,"msg":"The post_data parameter must be valid JSON"}' );
   }

这是最好的和有效的方式

function isJson($string) {
    return (json_decode($string) == null) ? false : true;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top