编程

PHP 8.6: JSON: json_decode 错误/异常消息现在会指示错误的位置

15 2026-03-12 16:57:00

在 PHP 8.6 中,json_decodejson_last_error_msg 函数会返回错误发生的行号和位置。在 PHP 8.6 之前,错误信息包含错误类型和描述,但不会包含解析时发生错误的具体位置。

从 PHP 8.6 开始,所有 JSON 解码失败都会尝试在 JSON 字符串中包含错误发生的位置信息。

$json = '[{';
json_decode($json); // null
json_last_error_msg();
// "Syntax error near location 1:3"

在 PHP 8.6 之前的版本中,json_last_error_msg() 函数仅在解码同一字符串失败时返回语法错误。

当使用 JSON_THROW_ON_ERROR 标志为 json_decode 函数启用异常处理时,抛出的 JsonException 异常消息将包含错误的位置信息。

$json = '[{';
json_decode($json, flags: JSON_THROW_ON_ERROR);
JsonException: Syntax error near location 1:3
$json = '[{';
try {
  json_decode($json, flags: JSON_THROW_ON_ERROR);
}
catch (\JsonException $ex) {
    echo $ex->getMessage(); // "Syntax error near location 1:3"
}

其他示例

json_decode("{\n\t  \"key1\": \"val1\",\n  \t\"key2\": \"val2\n}");
json_last_error_msg(); // "Control character error, possibly incorrectly encoded near location 3:12"
json_decode('{"numbers": [1, 2, 3], "strings": ["a", "b", "c"], "booleans": [true, false, true}');
json_last_error_msg(); // "State mismatch (invalid or malformed JSON) near location 1:82"
json_decode('[[[[[[[[[[42]]]]]]]]]]', depth: 6);
json_last_error_msg(); // "Maximum stack depth exceeded near location 1:6"
json_decode("\"a\xb0b\"");
json_last_error_msg(); // "Malformed UTF-8 characters, possibly incorrectly encoded near location 1:1"

向后兼容性影响

PHP 8.6 新增了从 JSON 错误处理中报告位置信息的功能。由于 PHP 没有公开底层 JSON 解析,因此无法将此功能移植到旧版本的 PHP。

json_last_error 函数在所有 PHP 版本中都报告相同的错误代码,从而确保与基于错误代码的断言兼容。