json_last_error_msg
Description
The json_last_error_msg of JSON for PHP returns the error string of the last json_encode() or json_decode() call.
Syntax
json_last_error_msg(): string
Return
Returns the error message on success, or "No error" if no error has occurred.
| Value | Constant | Description |
|---|---|---|
| 0 | JSON_ERROR_NONE | No error |
| 1 | JSON_ERROR_DEPTH | Maximum stack depth exceeded |
| 2 | JSON_ERROR_STATE_MISMATCH | State mismatch (invalid or malformed JSON) |
| 3 | JSON_ERROR_CTRL_CHAR | Control character error, possibly incorrectly encoded |
| 4 | JSON_ERROR_SYNTAX | Syntax error |
| 5 | JSON_ERROR_UTF8 | Malformed UTF-8 characters, possibly incorrectly encoded |
| 6 | JSON_ERROR_RECURSION | Recursion detected |
| 7 | JSON_ERROR_INF_OR_NAN | Inf and NaN cannot be JSON encoded |
| 8 | JSON_ERROR_UNSUPPORTED_TYPE | Type is not supported |
| 9 | JSON_ERROR_INVALID_PROPERTY_NAME | The decoded property name is invalid |
| 10 | JSON_ERROR_UTF16 | Single unpaired UTF-16 surrogate in unicode escape |
Examples
1 · JSON_ERROR_NONE
<? $return = json_last_error_msg(); echo $return;
No error
2 · JSON_ERROR_DEPTH
<?
$value =
[
1,
2,
[
1,
2,
[
1,
2
]
]
];
$flags = 0;
$depth = 2;
json_encode($value, $flags, $depth);
$return = json_last_error_msg();
echo $return;
Maximum stack depth exceeded
3 · JSON_ERROR_STATE_MISMATCH
<?
$json = '{"a":1]}';
json_decode($json);
$return = json_last_error_msg();
echo $return;
State mismatch (invalid or malformed JSON)
4 · JSON_ERROR_CTRL_CHAR
<? $json = "\""; json_decode($json); $return = json_last_error_msg(); echo $return;
Control character error, possibly incorrectly encoded
5 · JSON_ERROR_SYNTAX
<?
$json = "{'a':1}";
json_decode($json);
$return = json_last_error_msg();
echo $return;
Syntax error
6 · JSON_ERROR_UTF8
<? $value = "\xaa"; json_encode($value); $return = json_last_error_msg(); echo $return;
Malformed UTF-8 characters, possibly incorrectly encoded
7 · JSON_ERROR_RECURSION
<? $value[0] = &$value; json_encode($value); $return = json_last_error_msg(); echo $return;
Recursion detected
8 · JSON_ERROR_INF_OR_NAN
<?
$value =
[
INF,
NAN
];
json_encode($value);
$return = json_last_error_msg();
echo $return;
Inf and NaN cannot be JSON encoded
9 · JSON_ERROR_UNSUPPORTED_TYPE
<? $filename = $_SERVER["DOCUMENT_ROOT"] . "/assets/txt/1.txt"; $mode = "r"; $value = fopen($filename, $mode); fclose($value); json_encode($value); $return = json_last_error_msg(); echo $return;
Type is not supported
10 · JSON_ERROR_INVALID_PROPERTY_NAME
<?
$json = '{"\u0000":1}';
json_decode($json);
$return = json_last_error_msg();
echo $return;
The decoded property name is invalid
11 · JSON_ERROR_UTF16
<?
$json = '{"\udaaa":1}';
json_decode($json);
$return = json_last_error_msg();
echo $return;
Single unpaired UTF-16 surrogate in unicode escape