Solving:
Php function json_decode in case of json parsing errors returns null.
To catch errors use function json_last_error - returns the last error occurred ( int code )
(PHP 5 >= 5.5.0, PHP 7)
json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call
Example:$valid_json = '{"name":"Trololo"}';
$invalid_json = '{"name":"Trololo" ';
$obj = json_decode( $valid_json );
$obj = json_decode( $invalid_json );
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
Official Docs:
json_decode - http://php.net/manual/en/function.json-decode.php
json_last_error - http://php.net/manual/en/function.json-last-error.php
No comments:
Post a Comment