In PHP, json_last_error_msg() returns a readable text message for the last json_decode() or json_encode() error. If there was no error, it returns the string No error.
This function is the friendly cousin of json_last_error(). Instead of a number, it gives you a sentence such as Syntax error, which is perfect for logs, debug output and error messages.
Syntax
Call json_last_error_msg() with the values you need. Start with this line.
PHP
echo json_last_error_msg();
Call
What it does
json_last_error_msg()
Returns the message for the most recent JSON call.
json_decode('{oops}'); json_last_error_msg()
Returns Syntax error after a failed decode.
json_encode(NAN); json_last_error_msg()
Returns Inf and NaN cannot be JSON encoded after a failed encode.
json_last_error_msg() takes no arguments and always returns a string. Read the message right after the JSON call, because the next call resets it. It does not report errors from calls that use JSON_THROW_ON_ERROR.
Library declarations
PHP
json_last_error_msg(): string
Parameters
Parameter
Description
—
This function takes no parameters.
Return Value
Return Value
Description
string
A message such as No error, Syntax error, Maximum stack depth exceeded, Malformed UTF-8 characters, possibly incorrectly encoded, or Type is not supported.
PHP Examples
Example 1 — Read the Error Message
Decode valid and invalid JSON, and print the message after each call.
safeDecode() decodes the string and then checks json_last_error().
Valid JSON returns an array, so count() prints 2.
The broken JSON triggers the error branch, which prints the message from json_last_error_msg().
The text null is valid JSON, so there is no message, and the helper just returns null.
Frequently Asked Questions
It returns a text description of the last JSON error, like Syntax error or Maximum stack depth exceeded. When there is no error it returns No error.
Use json_last_error() when your code needs to make a decision, and json_last_error_msg() when you want to show or log a readable message. Many scripts use both together.
No. With that flag PHP throws a JsonException, and the exception already has the message through getMessage(). The global error state is not updated.
You will often see No error, Syntax error, Maximum stack depth exceeded, Malformed UTF-8 characters, possibly incorrectly encoded, Inf and NaN cannot be JSON encoded, and Type is not supported.
It is better to log it and show a simple friendly message to visitors. The technical text can confuse users and may reveal details about how your code handles data.