提问人:Kirk Ouimet 提问时间:5/18/2011 最后编辑:Madan SapkotaKirk Ouimet 更新时间:11/24/2023 访问量:557120
在PHP中检查字符串是否为JSON的最快方法?
Fastest way to check if a string is JSON in PHP?
问:
我需要一种非常非常快速的方法来检查字符串是否是 JSON。我觉得这不是最好的方法:
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
有没有性能爱好者想要改进这种方法?
答:
function isJson($string) {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
评论
{
[
6.5 = true, '300' = true, 9 = true
{}
[]
;
json_decode
isJson('0123')
false
0123
isJson('123')
true
123
null
function is_json($str){
return json_decode($str) != null;
}
检测到无效编码时 http://tr.php.net/manual/en/function.json-decode.php 返回值为 null。
评论
json_decode($str)!=null;
is_not_json
is_json('false')
is_json('[]')
false
$str === null || json_decode($str) !== null
使用json_decode
来“探测”它实际上可能不是最快的方法。如果它是一个深度嵌套的结构,那么实例化大量数组对象并将它们扔掉是浪费内存和时间。
因此,使用 preg_match
和 RFC4627正则表达式来确保有效性可能会更快:
// in JS:
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, '')));
在 PHP 中也是如此:
return !preg_match('/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]/',
preg_replace('/"(\\.|[^"\\\\])*"/', '', $json_string));
然而,没有足够的性能爱好者在这里为基准测试而烦恼。
评论
json_decode
PHP version : 5.5.34 Platform : Darwin -------------------------------------- test_json_decode : 5.608 sec. test_regex : 10.428 sec.
你真正需要做的就是这个......
if (is_object(json_decode($MyJSONArray)))
{
... do something ...
}
此请求甚至不需要单独的功能。只需is_object缠绕json_decode,然后继续前进。似乎这个解决方案让人们花了太多心思。
评论
is_array
is_object
is_object
json_decode
is_array
json_encode($array)
json_decode($str)
json_decode($str, true)
is_array(json_decode($str, true))
is_object(json_decode($MyJSONArray))
json_decode
json_decode
JSON_FORCE_OBJECT
This request does not require a separate function even
我不知道我的解决方案的性能或优雅,但这就是我正在使用的:
if (preg_match('/^[\[\{]\"/', $string)) {
$aJson = json_decode($string, true);
if (!is_null($aJson)) {
... do stuff here ...
}
}
由于我所有 JSON 编码的字符串都以 {“ 开头,因此使用正则表达式测试这一点就足够了。我对正则表达式一点也不流利,所以可能有更好的方法可以做到这一点。另外:strpos() 可能会更快。
只是想放弃我的傻瓜价值。
PS 刚刚更新了正则表达式字符串以查找 JSON 数组字符串。因此,它现在在字符串的开头查找 [“ 或 {”。/^[\[\{]\"/
问题的答案
该函数返回 JSON 编码和解码期间发生的最后一个错误。因此,检查有效 JSON 的最快方法是json_last_error
// 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
}
请注意,仅在 PHP >= 5.3.0 中受支持。json_last_error
检查确切错误的完整程序
在开发过程中了解确切的错误总是好的。这是根据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;
}
使用有效的 JSON INPUT 进行测试
$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]';
$output = json_validate($json);
print_r($output);
有效输出
Array
(
[0] => stdClass Object
(
[user_id] => 13
[username] => stack
)
[1] => stdClass Object
(
[user_id] => 14
[username] => over
)
)
使用无效的 JSON 进行测试
$json = '{background-color:yellow;color:#000;padding:10px;width:650px;}';
$output = json_validate($json);
print_r($output);
无效的输出
Syntax error, malformed JSON.
(PHP >= 5.2 && PHP < 5.3.0)的额外说明
由于 PHP 5.2 不支持,因此可以检查编码或解码是否返回 boolean 。下面是一个示例json_last_error
FALSE
// decode the JSON data
$result = json_decode($json);
if ($result === FALSE) {
// JSON is invalid
}
评论
((strlen($json) === 5) && ($json !== 'false'))
json_last_error
JSON_ERROR_NONE
PHP 8.3 (英语)
原生 PHP 函数
json_validate(string $json, int $depth = 512, int $flags = 0): bool
https://wiki.php.net/rfc/json_validate
PHP < 8.3
提供与上述结果类似的方法json_validate()
function is_json($string) {
return is_numeric($string)
|| in_array($string, ['null', 'true', 'false']
|| ( is_bool($string) && $string )
|| (
!empty($string)
&& is_string($string)
&& is_array(json_decode($string, true))
&& json_last_error() === JSON_ERROR_NONE
);
}
有时,查看 JSON 对象是否包含数据(对象或数组)会很有帮助
function has_json_data($string) {
return !empty($string)
&& is_string($string)
&& is_array($array = json_decode($string, true))
&& !empty($array)
&& json_last_error() === JSON_ERROR_NONE;
}
评论
'0'
if(is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE)){ // json is valid }else{ // not valid }
true
false
null
另一种简单的方法
function is_json($str)
{
return is_array(json_decode($str,true));
}
评论
json_decode($str,true)
早些时候我只是检查一个空值,这实际上是错误的。
$data = "ahad";
$r_data = json_decode($data);
if($r_data){//json_decode will return null, which is the behavior we expect
//success
}
上面的一段代码适用于字符串。但是,一旦我提供号码,它就会破裂。
$data = "1213145";
$r_data = json_decode($data);
if($r_data){//json_decode will return 1213145, which is the behavior we don't expect
//success
}
为了解决这个问题,我所做的非常简单。
$data = "ahad";
$r_data = json_decode($data);
if(($r_data != $data) && $r_data)
print "Json success";
else
print "Json error";
评论
我使用的最简单、最快的方法是遵循;
$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
这是因为如果输入的字符串不是 json 或无效的 json,则 json_decode() 返回 NULL。
验证JSON的简单函数
如果必须在多个位置验证 JSON,则始终可以使用以下函数。
function is_valid_json( $raw_json ){
return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes! thats it.
}
在上面的函数中,如果它是有效的 JSON,您将得到 true 作为回报。
评论
json_decode('null') == NULL
并且是有效的 JSON 值。null
PHP 5.2 兼容性的新函数,如果您需要成功解码的数据:
function try_json_decode( $json, & $success = null ){
// non-strings may cause warnings
if( !is_string( $json )){
$success = false;
return $json;
}
$data = json_decode( $json );
// output arg
$success =
// non-null data: success!
$data !== null ||
// null data from 'null' json: success!
$json === 'null' ||
// null data from ' null ' json padded with whitespaces: success!
preg_match('/^\s*null\s*$/', $json );
// return decoded or original data
return $success ? $data : $json;
}
用法:
$json_or_not = ...;
$data = try_json_decode( $json_or_not, $success );
if( $success )
process_data( $data );
else what_the_hell_is_it( $data );
一些测试:
var_dump( try_json_decode( array(), $success ), $success );
// ret = array(0){}, $success == bool(false)
var_dump( try_json_decode( 123, $success ), $success );
// ret = int(123), $success == bool(false)
var_dump( try_json_decode(' ', $success ), $success );
// ret = string(6) " ", $success == bool(false)
var_dump( try_json_decode( null, $success ), $success );
// ret = NULL, $success == bool(false)
var_dump( try_json_decode('null', $success ), $success );
// ret = NULL, $success == bool(true)
var_dump( try_json_decode(' null ', $success ), $success );
// ret = NULL, $success == bool(true)
var_dump( try_json_decode(' true ', $success ), $success );
// ret = bool(true), $success == bool(true)
var_dump( try_json_decode(' "hello" ', $success ), $success );
// ret = string(5) "hello", $success == bool(true)
var_dump( try_json_decode(' {"a":123} ', $success ), $success );
// ret = object(stdClass)#2 (1) { ["a"]=> int(123) }, $success == bool(true)
扩展这个答案 以下几点怎么样:
<?php
$json = '[{"user_id":13,"username":"stack"},{"user_id":14,"username":"over"}]';
//$json = '12';
function isJson($string) {
json_decode($string);
if(json_last_error() == JSON_ERROR_NONE) {
if(substr($string,0,1) == '[' && substr($string,-1) == ']') { return TRUE; }
else if(substr($string,0,1) == '{' && substr($string,-1) == '}') { return TRUE; }
else { return FALSE; }
}
}
echo isJson($json);
?>
评论
我们需要检查传递的字符串是否不是数字,因为在这种情况下json_decode不会引发错误。
function isJson($str) {
$result = false;
if (!preg_match("/^\d+$/", trim($str))) {
json_decode($str);
$result = (json_last_error() == JSON_ERROR_NONE);
}
return $result;
}
简单的方法是检查json结果。
$result = @json_decode($json,true);
if (is_array($result)) {
echo 'JSON is valid';
}else{
echo 'JSON is not valid';
}
在 GuzzleHttp 中:
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return mixed
* @throws \InvalidArgumentException if the JSON cannot be decoded.
* @link http://www.php.net/manual/en/function.json-decode.php
*/
function json_decode($json, $assoc = false, $depth = 512, $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
'json_decode error: ' . json_last_error_msg());
}
return $data;
}
/**
* Wrapper for JSON encoding that throws when an error occurs.
*
* @param mixed $value The value being encoded
* @param int $options JSON encode option bitmask
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @return string
* @throws \InvalidArgumentException if the JSON cannot be encoded.
* @link http://www.php.net/manual/en/function.json-encode.php
*/
function json_encode($value, $options = 0, $depth = 512)
{
$json = \json_encode($value, $options, $depth);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(
'json_encode error: ' . json_last_error_msg());
}
return $json;
}
如果你的字符串表示一个 json 数组或对象,这将返回 true:
function isJson($str) {
$json = json_decode($str);
return $json && $str != $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)
这是我能想到的最短的方法。
评论
isJson('hello')
return $json == '[]' || ...
json_decode
NULL
!is_null
return $json !== false && !is_null($json) && $str != $json;
在尝试解码 JSON 字符串之前,我们首先执行一些类型检查和字符串比较。这为我们提供了最佳性能,因为速度可能很慢。json_decode()
/**
* Returns true, when the given parameter is a valid JSON string.
*/
function is_json( $value ) {
// Numeric strings are always valid JSON.
if ( is_numeric( $value ) ) { return true; }
// A non-string value can never be a JSON string.
if ( ! is_string( $value ) ) { return false; }
// Any non-numeric JSON string must be longer than 2 characters.
if ( strlen( $value ) < 2 ) { return false; }
// "null" is valid JSON string.
if ( 'null' === $value ) { return true; }
// "true" and "false" are valid JSON strings.
if ( 'true' === $value ) { return true; }
if ( 'false' === $value ) { return true; }
// Any other JSON string has to be wrapped in {}, [] or "".
if ( '{' != $value[0] && '[' != $value[0] && '"' != $value[0] ) { return false; }
// Verify that the trailing character matches the first character.
$last_char = $value[strlen($value) -1];
if ( '{' == $value[0] && '}' != $last_char ) { return false; }
if ( '[' == $value[0] && ']' != $last_char ) { return false; }
if ( '"' == $value[0] && '"' != $last_char ) { return false; }
// See if the string contents are valid JSON.
return null !== json_decode( $value );
}
额外:使用此逻辑安全地对 JSON 进行双重解码
此函数使用相同的逻辑,但返回解码的 JSON 对象或原始值。
我在递归解码复杂对象的解析器中使用此函数。某些属性可能已由早期迭代解码。该函数会识别这一点,并且不会尝试再次对值进行双重解码。
/**
* Tests, if the given $value parameter is a JSON string.
* When it is a valid JSON value, the decoded value is returned.
* When the value is no JSON value (i.e. it was decoded already), then
* the original value is returned.
*/
function get_data( $value, $as_object = false ) {
if ( is_numeric( $value ) ) { return 0 + $value; }
if ( ! is_string( $value ) ) { return $value; }
if ( strlen( $value ) < 2 ) { return $value; }
if ( 'null' === $value ) { return null; }
if ( 'true' === $value ) { return true; }
if ( 'false' === $value ) { return false; }
if ( '{' != $value[0] && '[' != $value[0] && '"' != $value[0] ) { return $value; }
$json_data = json_decode( $value, $as_object );
if ( is_null( $json_data ) ) { return $value; }
return $json_data;
}
注意:当将非字符串传递给此 SO 问题中的任何其他解决方案时,您将获得性能显着下降 + 错误的返回值(甚至是致命错误)。此代码是无懈可击且高性能的。
评论
json_decode
if
我已经尝试了一些解决方案,但没有任何效果。我尝试这个简单的事情:
$isJson = json_decode($myJSON);
if ($isJson instanceof \stdClass || is_array($isJson)) {
echo("it's JSON confirmed");
} else {
echo("nope");
}
我认为这是一个很好的解决方案,因为没有第二个参数的 JSON 解码会给出一个对象。
编辑:如果您知道输入的内容,则可以根据需要调整此代码。就我而言,我知道我有一个以“{”开头的 Json,所以我不需要检查它是否是一个数组。
评论
应该是这样的:
function isJson($string)
{
// 1. Speed up the checking & prevent exception throw when non string is passed
if (is_numeric($string) ||
!is_string($string) ||
!$string) {
return false;
}
$cleaned_str = trim($string);
if (!$cleaned_str || !in_array($cleaned_str[0], ['{', '['])) {
return false;
}
// 2. Actual checking
$str = json_decode($string);
return (json_last_error() == JSON_ERROR_NONE) && $str && $str != $string;
}
单元测试
public function testIsJson()
{
$non_json_values = [
"12",
0,
1,
12,
-1,
'',
null,
0.1,
'.',
"''",
true,
false,
[],
'""',
'[]',
' {',
' [',
];
$json_values = [
'{}',
'{"foo": "bar"}',
'[{}]',
' {}',
' {} '
];
foreach ($non_json_values as $non_json_value) {
$is_json = isJson($non_json_value);
$this->assertFalse($is_json);
}
foreach ($json_values as $json_value) {
$is_json = isJson($json_value);
$this->assertTrue($is_json);
}
}
评论
ErrorException
这将完成:
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";
}
如其他答案所示,json_last_error(
) 返回上一个 json_decode() 中的任何错误。但是,在某些边缘用例中,仅此功能本身还不够全面。例如,如果您json_decode()
一个整数(例如:),或一个没有空格或其他字符(例如:)的数字字符串,则该函数不会捕获错误。123
"123"
json_last_error()
为了解决这个问题,我添加了一个额外的步骤,以确保我们的结果是对象或数组。如果不是,那么我们返回.json_decode()
false
若要查看此操作,请查看以下两个示例:
评论
"hello"
是一个有效的 JSON,它既不是对象也不是数组,就足够了json_last_error()
false
46783
null
嗨,这是我库中的一个小片段,在第一种情况下,我只是检查数据是否是 json,然后在正确解码时返回它,请注意性能的子 str 用法( 我还没有看到任何 json 文件不是以 { 或 [ 开头的
$input=trim($input);
if ((substr($input, 0, 1) == '{' && substr($input, -1) == '}') or (substr($input, 0, 1) == '[' && substr($input, -1) == ']')) {
$output = json_decode($input, 1);
if (in_array(gettype($output),['object','array'])) {
#then it's definitely JSON
}
}
评论
我的另一个建议:)
function isJson(string $string) {
return ($result = json_decode($string, true)) ? $result : $string;
}
这是我创建的一个高性能且简单的函数(在用于较大的字符串之前使用基本的字符串验证):json_decode
function isJson($string) {
$response = false;
if (
is_string($string) &&
($string = trim($string)) &&
($stringLength = strlen($string)) &&
(
(
stripos($string, '{') === 0 &&
(stripos($string, '}', -1) + 1) === $stringLength
) ||
(
stripos($string, '[{') === 0 &&
(stripos($string, '}]', -1) + 2) === $stringLength
)
) &&
($decodedString = json_decode($string, true)) &&
is_array($decodedString)
) {
$response = true;
}
return $response;
}
将 PHPBench 与以下类一起使用,可以获得以下结果:
<?php
declare(strict_types=1);
/**
* @Revs(1000)
* @Iterations(100)
*/
class BenchmarkJson
{
public function benchCatchValid(): bool
{
$validJson = '{"validJson":true}';
try {
json_decode($validJson, true, 512, JSON_THROW_ON_ERROR);
return true;
} catch(\JsonException $exception) {}
return false;
}
public function benchCatchInvalid(): bool
{
$invalidJson = '{"invalidJson"';
try {
json_decode($invalidJson, true, 512, JSON_THROW_ON_ERROR);
return true;
} catch(\JsonException $exception) {}
return false;
}
public function benchLastErrorValid(): bool
{
$validJson = '{"validJson":true}';
json_decode($validJson, true);
return (json_last_error() === JSON_ERROR_NONE);
}
public function benchLastErrorInvalid(): bool
{
$invalidJson = '{"invalidJson"';
json_decode($invalidJson, true);
return (json_last_error() === JSON_ERROR_NONE);
}
public function benchNullValid(): bool
{
$validJson = '{"validJson":true}';
return (json_decode($validJson, true) !== null);
}
public function benchNullInvalid(): bool
{
$invalidJson = '{"invalidJson"';
return (json_decode($invalidJson, true) !== null);
}
}
6 subjects, 600 iterations, 6,000 revs, 0 rejects, 0 failures, 0 warnings
(best [mean mode] worst) = 0.714 [1.203 1.175] 1.073 (μs)
⅀T: 721.504μs μSD/r 0.089μs μRSD/r: 7.270%
suite: 1343ab9a3590de6065bc0bc6eeb344c9f6eba642, date: 2020-01-21, stime: 12:50:14
+---------------+-----------------------+-----+------+-----+------------+---------+---------+---------+---------+---------+--------+-------+
| benchmark | subject | set | revs | its | mem_peak | best | mean | mode | worst | stdev | rstdev | diff |
+---------------+-----------------------+-----+------+-----+------------+---------+---------+---------+---------+---------+--------+-------+
| BenchmarkJson | benchCatchValid | 0 | 1000 | 100 | 2,980,168b | 0.954μs | 1.032μs | 1.016μs | 1.428μs | 0.062μs | 6.04% | 1.33x |
| BenchmarkJson | benchCatchInvalid | 0 | 1000 | 100 | 2,980,184b | 2.033μs | 2.228μs | 2.166μs | 3.001μs | 0.168μs | 7.55% | 2.88x |
| BenchmarkJson | benchLastErrorValid | 0 | 1000 | 100 | 2,980,184b | 1.076μs | 1.195μs | 1.169μs | 1.616μs | 0.083μs | 6.97% | 1.54x |
| BenchmarkJson | benchLastErrorInvalid | 0 | 1000 | 100 | 2,980,184b | 0.785μs | 0.861μs | 0.863μs | 1.132μs | 0.056μs | 6.54% | 1.11x |
| BenchmarkJson | benchNullValid | 0 | 1000 | 100 | 2,980,168b | 0.985μs | 1.124μs | 1.077μs | 1.731μs | 0.114μs | 10.15% | 1.45x |
| BenchmarkJson | benchNullInvalid | 0 | 1000 | 100 | 2,980,184b | 0.714μs | 0.775μs | 0.759μs | 1.073μs | 0.049μs | 6.36% | 1.00x |
+---------------+-----------------------+-----+------+-----+------------+---------+---------+---------+---------+---------+--------+-------+
结论:检查json是否有效的最快方法是返回。json_decode($json, true) !== null)
评论
昨天,我在工作中遇到类似的事情后发现了这个问题。最后,我的解决方案是上述一些方法的混合体:
function is_JSON($string) {
return (is_null(json_decode($string))) ? FALSE : TRUE;
}
评论
if (is_null($string)) return TRUE;
return is_null(json_decode($string));
true
$string
return !is_null(json_decode($string));
//Tested thoroughly, Should do the job:
public static function is_json(string $json):bool
{
json_decode($json);
if (json_last_error() === JSON_ERROR_NONE) {
return true;
}
return false;
}
这是我推荐的
if (!in_array(substr($string, 0, 1), ['{', '[']) || !in_array(substr($string, -1), ['}', ']'])) {
return false;
} else {
json_decode($string);
return (json_last_error() === JSON_ERROR_NONE);
}
评论
2352
"foo"
null
function isJson($string) {
$obj = json_decode($string);
return json_last_error() === JSON_ERROR_NONE && gettype($obj ) == "object";
}
这有效,并且不会对数字返回 true
最新更新
如果JSON很长,并且不需要使用$obj,则上述解决方案的性能不佳
如果你只是想检查,最好使用下面的功能
function isJson($string) {
if(is_numeric($string)) return false;
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
评论
更新:json_validate() 将在 PHP 8.3 中上线
仅供参考:
我正在研究一个 RFC,以在 php 中添加一个新函数,该函数能够仅验证 json 字符串,而无需在此过程中生成对象/数组。
为什么使用仅验证函数?因为 json_decode() 在解析 json-string 时会创建一个数组/对象,从而影响正在使用的内存量;这意味着在验证 JSON 字符串时可以达到最大内存限制。
为了给你一个想法,请检查以下代码 performance_test_json_validate()_vs_json_decode():
在该测试中,我们可以看到新函数 json_validate() 使用 0 MB 来验证 json-string,而 json_decode() 需要 109 MB 来执行此操作(因为它在解析时会创建一个内存中的数组/对象。
目前这是正在进行的工作,但我发布这个是因为我对你的意见感兴趣(不是你认为是否值得拥有它,我的意思是,从技术角度来看)。
Github:https://github.com/php/php-src/pull/9399
RFC(工作进行中):https://wiki.php.net/rfc/json_validate
期待您对此的意见/支持。
提前致谢。
json_validate() 函数的 RFC 已经实现,并将成为 PHP 8.3 的一部分
这种方法将是实现问题要求的最快和最有效的方法。
评论
虽然仍在开发中的PHP 8.3将具有新的内存效率功能,但由于Symfony Polyfill组件的出色表现,您可以将其与较旧的PHP版本(7.1及更新版本)一起使用。json_validate()
只需将以下包添加到您的项目中:
composer require symfony/polyfill-php83
并在您的应用程序中使用它:
if (json_validate($data)) {
// do sometihng
}
由于这种方法,您可以在旧应用程序中使用新的 PHP 功能,并迁移到 PHP 8.3,而无需将来进行任何代码更改,因为您的代码将在可用时自动使用内置函数。
评论
json_decode
json_decode