Function name: json_last_error_msg()
Function description: The json_last_error_msg() function returns the readability description of the error that occurred during the previous JSON decoding process.
Applicable version: PHP 5.5.0 and above
Syntax: string json_last_error_msg ( void )
Return value: Returns a string representing the readability description of the error that occurred during the previous JSON decoding process. If no error occurs, an empty string is returned.
Example:
<?php $jsonData = '{"name":"John", "age":30, "city":"New York"}'; // 尝试解码JSON 数据$decodedData = json_decode($jsonData); // 检查解码是否成功if ($decodedData === null) { // 获取错误信息$error = json_last_error_msg(); echo "JSON 解码失败。错误信息:$error"; } else { // 解码成功echo "JSON 解码成功。"; } ?>
Output:
JSON decoding failed. Error message: Syntax error
Description: In the example above, we try to decode a JSON data containing the wrong syntax. The decoding process fails due to syntax errors in the JSON data. Using the json_last_error_msg() function, we can get a readability description of the error, so that we can better understand the cause of the error. In this example, the output is "Syntax error", indicating that there is a syntax error in the JSON data. If JSON decodes successfully, the function returns an empty string.