SoFunction
Updated on 2025-03-06

Exception handling of built-in functions json_encode and json_decode in php

In php, json_encode and json_decode are very commonly used functions. For specific usage, you can view the relevant documents. Here we mainly talk about error handling.

Usually, we may not pay much attention to error handling when using these two methods. Sometimes if the incoming parameters are incorrect, it will cause an error. Here is how to handle errors:

json_last_error —Returns the last error that occurred. If so, returns the last error that occurred during JSON encoding and decoding.

int json_last_error ( void )
constant meaning Availability
JSON_ERROR_NONE No error occurred
JSON_ERROR_DEPTH Maximum stack depth reached
JSON_ERROR_STATE_MISMATCH Invalid or exceptional JSON
JSON_ERROR_CTRL_CHAR Control character error, maybe it's an incorrect encoding
JSON_ERROR_SYNTAX Syntax error
JSON_ERROR_UTF8 Exception of UTF-8 characters, perhaps because of incorrect encoding. PHP 5.3.3
JSON_ERROR_RECURSION One or more recursive references in the value to be encoded PHP 5.5.0
JSON_ERROR_INF_OR_NAN One or more NAN or INF values in the value to be encoded PHP 5.5.0
JSON_ERROR_UNSUPPORTED_TYPE The specified type, the value cannot be encoded. PHP 5.5.0
JSON_ERROR_INVALID_PROPERTY_NAME The specified attribute name cannot be encoded. PHP 7.0.0
JSON_ERROR_UTF16 Deformed UTF-16 characters, probably because of incorrect character encoding. PHP 7.0.0
<?php
// A valid json string$json[] = '{"Organization": "PHP Documentation Team"}';
 
// An invalid json string will cause a syntax error. In this example we use ' instead of " as quotes$json[] = "{'Organization': 'PHP Documentation Team'}";
 
 
foreach ($json as $string) {
    echo 'Decoding: ' . $string;
    json_decode($string);
 
    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;
    }
 
    echo PHP_EOL;
}

php official reference document: /manual/zh/

This is the article about the exception handling of built-in functions json_encode and json_decode in PHP. This is the end. For more related contents of PHP handling of json_encode and json_decode exceptions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!