在 PHP 中检查字符串是否为 JSON 的最快方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6041741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:11:25  来源:igfitidea点击:

Fastest way to check if a string is JSON in PHP?

phpjsonerror-handlingjson-deserializationjsonresult

提问by Kirk Ouimet

I need a really, really fast method of checking if a string is JSON or not. I feel like this is not the best way:

我需要一种非常非常快速的方法来检查字符串是否为 JSON。我觉得这不是最好的方法:

function isJson($string) {
    return ((is_string($string) &&
            (is_object(json_decode($string)) ||
            is_array(json_decode($string))))) ? true : false;
}

Any performance enthusiasts out there want to improve this method?

有没有性能爱好者想要改进这种方法?

回答by Henrik P. Hessel

function isJson($string) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

回答by Madan Sapkota

Answer to the Question

回答问题

The function json_last_errorreturns the last error occurred during the JSON encoding and decoding. So the fastest way to check the valid JSON is

该函数json_last_error返回 JSON 编码和解码过程中发生的最后一个错误。所以检查有效 JSON 的最快方法是

// decode the JSON data
// set second parameter boolean TRUE for associative array output.
$result = json_decode($json);

if (json_last_error() === JSON_ERROR_NONE) {
    // JSON is valid
}

// OR this is equivalent

if (json_last_error() === 0) {
    // JSON is valid
}

Note that json_last_erroris supported in PHP >= 5.3.0 only.

请注意,json_last_error仅在 PHP >= 5.3.0 中受支持。

Full program to check the exact ERROR

检查确切错误的完整程序

It is always good to know the exact error during the development time. Here is full program to check the exact error based on PHP docs.

在开发期间知道确切的错误总是好的。这是基于 PHP 文档检查确切错误的完整程序。

function json_validate($string)
{
    // decode the JSON data
    $result = json_decode($string);

    // switch and check possible JSON errors
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            $error = ''; // JSON is valid // No error has occurred
            break;
        case JSON_ERROR_DEPTH:
            $error = 'The maximum stack depth has been exceeded.';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            $error = 'Invalid or malformed JSON.';
            break;
        case JSON_ERROR_CTRL_CHAR:
            $error = 'Control character error, possibly incorrectly encoded.';
            break;
        case JSON_ERROR_SYNTAX:
            $error = 'Syntax error, malformed JSON.';
            break;
        // PHP >= 5.3.3
        case JSON_ERROR_UTF8:
            $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_RECURSION:
            $error = 'One or more recursive references in the value to be encoded.';
            break;
        // PHP >= 5.5.0
        case JSON_ERROR_INF_OR_NAN:
            $error = 'One or more NAN or INF values in the value to be encoded.';
            break;
        case JSON_ERROR_UNSUPPORTED_TYPE:
            $error = 'A value of a type that cannot be encoded was given.';
            break;
        default:
            $error = 'Unknown JSON error occured.';
            break;
    }

    if ($error !== '') {
        // throw the Exception or exit // or whatever :)
        exit($error);
    }

    // everything is OK
    return $result;
}

Testing with Valid JSON INPUT

使用有效的 JSON INPUT 进行测试

$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]';
$output = json_validate($json);
print_r($output);

Valid OUTPUT

有效输出

Array
(
    [0] => stdClass Object
        (
            [user_id] => 13
            [username] => stack
        )

    [1] => stdClass Object
        (
            [user_id] => 14
            [username] => over
        )
)

Testing with invalid JSON

使用无效的 JSON 进行测试

$json = '{background-color:yellow;color:#000;padding:10px;width:650px;}';
$output = json_validate($json);
print_r($output);

Invalid OUTPUT

无效的输出

Syntax error, malformed JSON.

Extra note for (PHP >= 5.2 && PHP < 5.3.0)

(PHP >= 5.2 && PHP < 5.3.0) 的额外说明

Since json_last_erroris not supported in PHP 5.2, you can check if the encoding or decoding returns boolean FALSE. Here is an example

由于json_last_errorPHP 5.2 不支持,您可以检查编码或解码是否返回 boolean FALSE。这是一个例子

// decode the JSON data
$result = json_decode($json);
if ($result === FALSE) {
    // JSON is invalid
}

Hope this is helpful. Happy Coding!

希望这是有帮助的。快乐编码!

回答by user1653711

All you really need to do is this...

你真正需要做的就是这个......

if (is_object(json_decode($MyJSONArray))) 
    { 
        ... do something ...
    }

This request does not require a separate function even. Just wrap is_object around json_decode and move on. Seems this solution has people putting way too much thought into it.

这个请求甚至不需要单独的函数。只需将 is_object 包裹在 json_decode 周围并继续。似乎这个解决方案让人们对其进行了太多思考。

回答by mario

Using json_decodeto "probe" it might not actually be the fastest way. If it's a deeply nested structure, then instantiating a lot of objects of arrays to just throw them away is a waste of memory and time.

使用json_decode“探测”它实际上可能不是最快的方法。如果是深度嵌套的结构,那么实例化很多数组对象就扔掉,是浪费内存和时间。

So it might be faster to use preg_matchand the RFC4627regexto also ensure validity:

所以它可能是更快地使用preg_matchRFC4627的正则表达式确保有效性

  // in JS:
  var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
         text.replace(/"(\.|[^"\])*"/g, '')));

The same in PHP:

在 PHP 中相同:

  return !preg_match('/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/',
       preg_replace('/"(\.|[^"\\])*"/', '', $json_string));

Not enough of a performance enthusiast to bother with benchmarks here however.

然而,没有足够的性能爱好者来打扰这里的基准测试。

回答by Cyril

This will return trueif your string represents a json array or object:

如果您的字符串表示json 数组或对象,这将返回true

function isJson($str) {
    $json = json_decode($str);
    return $json && $str != $json;
}

It rejects json strings that only contains a number, string or boolean, although those strings are technically valid json.

它拒绝仅包含数字、字符串或布尔值的 json 字符串,尽管这些字符串在技术上是有效的 json。

var_dump(isJson('{"a":5}')); // bool(true)
var_dump(isJson('[1,2,3]')); // bool(true)
var_dump(isJson('1')); // bool(false)
var_dump(isJson('1.5')); // bool(false)
var_dump(isJson('true')); // bool(false)
var_dump(isJson('false')); // bool(false)
var_dump(isJson('null')); // bool(false)
var_dump(isJson('hello')); // bool(false)
var_dump(isJson('')); // bool(false)

It is the shortest way I can come up with.

这是我能想到的最短的方法。

回答by Mohammad Mursaleen

The simplest and fastest way that I use is following;

我使用的最简单和最快的方法是:

$json_array = json_decode( $raw_json , true );

if( $json_array == NULL )   //check if it was invalid json string
    die ('Invalid');  // Invalid JSON error

 // you can execute some else condition over here in case of valid JSON

It is because json_decode()returns NULL if the entered string is not json or invalid json.

这是因为如果输入的字符串不是 json 或无效的 json ,则 json_decode()返回 NULL。



Simple function to validate JSON

验证 JSON 的简单函数

If you have to validate your JSON in multiple places, you can always use the following function.

如果您必须在多个地方验证您的 JSON,您始终可以使用以下函数。

function is_valid_json( $raw_json ){
    return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it.
}

In the above function, you will get true in return if it is a valid JSON.

在上面的函数中,如果它是一个有效的 JSON,你将得到 true 作为回报。

回答by AhmetB - Google

function is_json($str){ 
    return json_decode($str) != null;
}

http://tr.php.net/manual/en/function.json-decode.phpreturn value is null when invalid encoding detected.

http://tr.php.net/manual/en/function.json-decode.php检测到无效编码时返回值为空。

回答by upful

You must validate your input to make sure the string you pass is not empty and is, in fact, a string. An empty string is not valid JSON.

您必须验证您的输入以确保您传递的字符串不为空,并且实际上是一个字符串。空字符串不是有效的 JSON。

function is_json($string) {
  return !empty($string) && is_string($string) && is_array(json_decode($string, true)) && json_last_error() == 0;
}

I think in PHP it's more important to determine if the JSON object even hasdata, because to use the data you will need to call json_encode()or json_decode(). I suggest denying empty JSON objects so you aren't unnecessarily running encodes and decodes on empty data.

我认为在 PHP 中更重要的是确定 JSON 对象是否有数据,因为要使用数据,您需要调用json_encode()json_decode(). 我建议拒绝空的 JSON 对象,这样您就不会不必要地对空数据运行编码和解码。

function has_json_data($string) {
  $array = json_decode($string, true);
  return !empty($string) && is_string($string) && is_array($array) && !empty($array) && json_last_error() == 0;
}

回答by Lewis Donovan

This will do it:

这将做到:

function isJson($string) {
    $decoded = json_decode($string); // decode our JSON string
    if ( !is_object($decoded) && !is_array($decoded) ) {
        /*
        If our string doesn't produce an object or array
        it's invalid, so we should return false
        */
        return false;
    }
    /*
    If the following line resolves to true, then there was
    no error and our JSON is valid, so we return true.
    Otherwise it isn't, so we return false.
    */
    return (json_last_error() == JSON_ERROR_NONE);
}

if ( isJson($someJsonString) ) {
    echo "valid JSON";
} else {
    echo "not valid JSON";
}

As shown in other answers, json_last_error()returns any error from our last json_decode(). However there are some edge use cases where this function alone is not comprehensive enough. For example, if you json_decode()an integer (eg: 123), or a string of numbers with no spaces or other characters (eg: "123"), the json_last_error()function will not catch an error.

如其他答案所示,json_last_error()返回上次 json_decode() 的任何错误。但是,在某些边缘用例中,仅凭此功能还不够全面。例如,如果您json_decode()是一个整数(例如:)123,或一串没有空格或其他字符的数字(例如:)"123",该json_last_error()函数将不会捕获错误。

To combat this, I've added an extra step that ensures the result of our json_decode()is either an object or an array. If it's not, then we return false.

为了解决这个问题,我添加了一个额外的步骤,以确保我们的结果json_decode()是一个对象或一个数组。如果不是,那么我们返回false

To see this in action, check these two examples:

要查看此操作,请查看以下两个示例:

回答by Rameez Rami

Easy method is to check the json result..

简单的方法是检查json结果..

$result = @json_decode($json,true);
    if (is_array($result)) {
        echo 'JSON is valid';
    }else{
        echo 'JSON is not valid';
    }