大网数据广告活动
PHP 语言与运行手册

simdjson_is_valid · Check if a JSON string is valid

· 52CE 我爱测

simdjson_is_valid — Check if a JSON string is valid

simdjson_is_valid

(PECL simdjson >= 2.0.0)

simdjson_is_valid — Check if a JSON string is valid

说明

function simdjson_is_valid(string $json, int $depth = 512): bool

Takes a JSON encoded string and returns true if it is valid.

参数

json

The json string being validated.

This function only works with UTF-8 encoded strings.

This function validates inputs which json_decode() can decode, provided that they are less than 4 GiB long.

depth

Maximum nesting depth of the structure being validated. The value must be greater than 0, and less than or equal to 2147483647. Callers should use reasonably small values, because larger depths require more buffer space and will increase the recursion depth, unlike the current json_decode() implementation.

返回值

Returns true if json is a valid JSON string, false otherwise.

错误/异常

If json is longer than 4 GiB, a SimdJsonException is thrown as of PECL simdjson 2.1.0, while previously, a RuntimeException was thrown.

If depth is outside the allowed range, a SimdJsonValueError is thrown as of PECL simdjson 3.0.0, while previously, an error of level E_WARNING was raised.

示例

示例 #1 simdjson_decode() examples

<?php
$json = '{"a":1,"b":2,"c":3}';
$invalidJson = '{"a":1,"b":2,"c":';

var_dump(simdjson_is_valid($json));
var_dump(simdjson_is_valid($invalidJson));

?>

以上示例会输出:

bool(true)
bool(false)

示例 #2 depth errors

<?php
// Encode some data with a maximum depth of 4
// (array -> array -> array -> string)
$json = json_encode(
    [
        1 => [
            'English' => [
                'One',
                'January'
            ],
            'French' => [
                'Une',
                'Janvier'
            ]
        ]
    ]
);

// Show the errors for different depths.
var_dump(simdjson_is_valid($json, 4));
var_dump(simdjson_is_valid($json, 3));
?>

以上示例会输出:

bool(true)
bool(false)

注释

注意:

The JSON spec is not JavaScript, but a subset of JavaScript.

注意:

In the event of a failure to decode, a SimdJsonException is thrown and SimdJsonException::getCode() and SimdJsonException::getMessage() can be used to determine the exact nature of the error.

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。