downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Judy> <json_encode
[edit] Last updated: Fri, 25 May 2012

view this page in

json_last_error

(PHP 5 >= 5.3.0)

json_last_errorRetourne la dernière erreur JSON

Description

int json_last_error ( void )

json_last_error() retourne la dernière erreur, s'il y en a eu, survenue lors de la dernière opération d'encodage/décodage JSON.

Liste de paramètres

Cette fonction ne contient aucun paramètre.

Valeurs de retour

Retourne une des constantes suivantes :

Codes d'erreur JSON
Constante Signification Disponibilité
JSON_ERROR_NONE Aucune erreur n'est survenue  
JSON_ERROR_DEPTH La profondeur maximale de la pile a été atteinte  
JSON_ERROR_STATE_MISMATCH JSON invalide ou mal formé  
JSON_ERROR_CTRL_CHAR Erreur lors du contrôle des caractères ; probablement un encodage incorrect  
JSON_ERROR_SYNTAX Erreur de syntaxe  
JSON_ERROR_UTF8 Caractères UTF-8 malformés, possiblement mal encodés PHP 5.3.3

Exemples

Exemple #1 Exemple avec json_last_error()

<?php
// Une chaîne JSON valide
$json[] = '{"Organisation": "Équipe de Documentation PHP"}';

// Une chaîne json invalide qui va générer une erreur de syntaxe,
// ici, utilisation de ' au lieu de "
$json[] = "{'Organisation': 'Équipe de Documentation PHP'}";

foreach (
$json as $string) {
    echo 
'Décodage : ' $string;
    
json_decode($string);

    switch (
json_last_error()) {
        case 
JSON_ERROR_NONE:
            echo 
' - Aucune erreur';
        break;
        case 
JSON_ERROR_DEPTH:
            echo 
' - Profondeur maximale atteinte';
        break;
        case 
JSON_ERROR_STATE_MISMATCH:
            echo 
' - Inadéquation des modes ou underflow';
        break;
        case 
JSON_ERROR_CTRL_CHAR:
            echo 
' - Erreur lors du contrôle des caractères';
        break;
        case 
JSON_ERROR_SYNTAX:
            echo 
' - Erreur de syntaxe ; JSON malformé';
        break;
        case 
JSON_ERROR_UTF8:
            echo 
' - Caractères UTF-8 malformés, probablement une erreur d\'encodage';
        break;
        default:
            echo 
' - Erreur inconnue';
        break;
    }

    echo 
PHP_EOL;
}
?>

L'exemple ci-dessus va afficher :

Décodage : {"Organisation": "Équipe de Documentation PHP"} - Aucune erreur
Décodage : {'Organisation': 'Équipe de Documentation PHP'} - Erreur de syntaxe ; JSON malformé

Exemple #2 Exemple avec json_last_error() et json_encode()

<?php
// Une séquence UTF8 invalide
$text "\xB1\x31";

$json  json_encode($text);
$error json_last_error();

var_dump($json$error === JSON_ERROR_UTF8);
?>

L'exemple ci-dessus va afficher :

string(4) "null"
bool(true)

Voir aussi



add a note add a note User Contributed Notes json_last_error
jimmetry at gmail dot com 23-Nov-2011 09:16
While this can obviously change between versions, the current error codes are as follows:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

I'm only posting these for people who may be trying to understand why specific JSON files are not being decoded. Please do not hard-code these numbers into an error handler routine.
lior at mytopia dot com 09-Mar-2009 05:17
For those of you who prefer a more object oriented approach (as I do), here is a fairly simple wrapper that handles errors using exceptions:

<?php

class JSON
{
    public static function
Encode($obj)
    {
        return
json_encode($obj);
    }
   
    public static function
Decode($json, $toAssoc = false)
    {
       
$result = json_decode($json, $toAssoc);
        switch(
json_last_error())
        {
            case
JSON_ERROR_DEPTH:
               
$error ' - Maximum stack depth exceeded';
                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_NONE:
            default:
               
$error = '';                   
        }
        if (!empty(
$error))
            throw new
Exception('JSON Error: '.$error);       
       
        return
$result;
    }
}

?>

 
show source | credits | sitemap | contact | advertising | mirror sites