PHP - Fonction json_last_error_msg ()

La fonction json_last_error_msg () peut renvoyer une chaîne d'erreur du dernier appel json_encode () ou json_decode ().

Syntaxe

string json_last_error_msg( void )

La fonction json_last_error_msg () peut renvoyer un message d'erreur en cas de succès, "No Error" si aucune erreur ne s'est produite, ou false en cas d'échec. Cette fonction n'a aucun paramètre.

Exemple 1

<?php
   $json = '{"name": "Adithya", "age": 20 }';

   $decode = json_decode($json, true);
   $last_error = json_last_error_msg();
   if(strtolower($last_error) != "No Error") {
      echo "ERROR: " . $last_error; die; 
   }
?>

Production

ERROR: No error

Exemple 2

<?php
   $json = '{"site":"dev.tutorialspoint.com","topics":{"PHP":"Y","JSON":"Y"]}';
   print("\nInput: ".$json."\n");

   $array = json_decode($json,true);

   if(json_last_error() == JSON_ERROR_NONE) {
      print("\nOutput Array:\n");
      print(" Type: " . gettype($array) . "\n");
      print(" Size: " . count($array) . "\n");
      print(" ['site']: " . $array["site"] . "\n");
      print(" ['topics']['JSON']: " . $array["topics"]["JSON"] . "\n");

      print("\n Output Array Dump:\n");
      var_dump($array);
   } else {
      print("\n json_decode() error: " . json_last_error_msg(). "\n");
   }
?>

Production

Input: {"site":"dev.tutorialspoint.com","topics":{"PHP":"Y","JSON":"Y"]}

json_decode() error: State mismatch (invalid or malformed JSON)