json_last_error_msg

(PHP 5 >= 5.5.0)

json_last_error_msgGibt die Fehlermeldung des letzten Aufrufs von json_encode oder json_decode() zur├╝ck

Beschreibung

string json_last_error_msg ( void )

Parameter-Liste

Diese Funktion hat keine Parameter.

R├╝ckgabewerte

Gibt bei Erfolg die Fehlermeldung oder NULL mit falschen Parametern.

Siehe auch

add a note add a note

User Contributed Notes 4 notes

up
16
Anonymous
1 year ago
if (!function_exists('json_last_error_msg')) {
    function json_last_error_msg() {
        static $errors = array(
            JSON_ERROR_NONE             => null,
            JSON_ERROR_DEPTH            => 'Maximum stack depth exceeded',
            JSON_ERROR_STATE_MISMATCH   => 'Underflow or the modes mismatch',
            JSON_ERROR_CTRL_CHAR        => 'Unexpected control character found',
            JSON_ERROR_SYNTAX           => 'Syntax error, malformed JSON',
            JSON_ERROR_UTF8             => 'Malformed UTF-8 characters, possibly incorrectly encoded'
        );
        $error = json_last_error();
        return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
    }
}
up
3
seregynp at gmail dot com
6 months ago
Watch out !

In case no error occurred, 'No error' still returned !

So when upgrading to php 5.5, unexpected behavior can be:

<?php
if ($error = json_last_error_msg()) {
   throw new \
LogicException(sprintf("Failed to parse json string '%s', error: '%s'", $this->data, $error));
}

// in php 5.5 exception will be thrown, while as in older version not
?>
up
3
Ess
1 year ago
If function not exists

<?php
if (!function_exists('json_last_error_msg'))
    function
json_last_error_msg()
    {
        switch (
json_last_error()) {
            default:
                return;
            case
JSON_ERROR_DEPTH:
               
$error = 'Maximum stack depth exceeded';
            break;
            case
JSON_ERROR_STATE_MISMATCH:
               
$error = 'Underflow or the modes mismatch';
            break;
            case
JSON_ERROR_CTRL_CHAR:
               
$error = 'Unexpected control character found';
            break;
            case
JSON_ERROR_SYNTAX:
               
$error = 'Syntax error, malformed JSON';
            break;
            case
JSON_ERROR_UTF8:
               
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
        }
        throw new
Exception($error);
    }
?>
up
1
Anonymous
9 days ago
seregynp :
a better way to test JSON
<?php
$json
= json_decode('wrong json');

if (
$json === null && json_last_error() !== JSON_ERROR_NONE) {
     throw new \
LogicException(sprintf("Failed to parse json string '%s', error: '%s'", $json , json_last_error_msg()));
}
?>
To Top