json_last_error

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

json_last_error返回最后发生的错误

说明

json_last_error ( ) : int

如果有,返回 JSON 编码解码时最后发生的错误。

参数

此函数没有参数。

返回值

返回一个整型(integer),这个值会是以下的常量之一:

JSON 错误码
常量 含义 可用性
JSON_ERROR_NONE 没有错误发生  
JSON_ERROR_DEPTH 到达了最大堆栈深度  
JSON_ERROR_STATE_MISMATCH 无效或异常的 JSON  
JSON_ERROR_CTRL_CHAR 控制字符错误,可能是编码不对  
JSON_ERROR_SYNTAX 语法错误  
JSON_ERROR_UTF8 异常的 UTF-8 字符,也许是因为不正确的编码。 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 指定的类型,值无法编码。 PHP 5.5.0
JSON_ERROR_INVALID_PROPERTY_NAME 指定的属性名无法编码。 PHP 7.0.0
JSON_ERROR_UTF16 畸形的 UTF-16 字符,可能因为字符编码不正确。 PHP 7.0.0

范例

Example #1 json_last_error() 例子

<?php
// 一个有效的 json 字符串
$json[] = '{"Organization": "PHP Documentation Team"}';

// 一个无效的 json 字符串会导致一个语法错误,在这个例子里我们使用 ' 代替了 " 作为引号
$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;
}
?>

以上例程会输出:

Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

Example #2 json_encode()json_last_error()

<?php
// 无效的 UTF8 序列
$text "\xB1\x31";

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

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

以上例程会输出:

string(4) "null"
bool(true)

参见

User Contributed Notes

wedge at atlanteans dot net 27-Mar-2018 02:15
here is a small updated version of utf8ize that has the following addition :
* It uses iconv instead of utf8_encode for potentially better result.
* It adds the support of objects variable
* It also update array key value (in a case I met I had to utf8ize the key as well as those were generated from a user input value)

Here is the code.

<?php
   
function utf8ize($d) {
        if (
is_array($d)) {
            foreach (
$d as $k => $v) {
                unset(
$d[$k]);
       
$d[utf8ize($k)] = utf8ize($v);
            }
        } else if (
is_object($d)) {
       
$objVars = get_object_vars($d);
        foreach(
$objVars as $key => $value) {
       
$d->$key = utf8ize($value);
        }       
    } else if (
is_string ($d)) {
            return
iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($d));
        }
        return
$d;
    }
?>
msxcms at bmforum dot com 16-Jun-2017 09:12
use this code with mb_convert_encoding, you can json_encode some corrupt UTF-8 chars

    function safe_json_encode($value, $options = 0, $depth = 512) {
        $encoded = json_encode($value, $options, $depth);
        if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
            $encoded = json_encode(utf8ize($value), $options, $depth);
        }
        return $encoded;
    }

    function utf8ize($mixed) {
        if (is_array($mixed)) {
            foreach ($mixed as $key => $value) {
                $mixed[$key] = utf8ize($value);
            }
        } elseif (is_string($mixed)) {
            return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
        }
        return $mixed;
    }
George Dimitriadis 28-Sep-2016 08:27
Just adding this note since I had to code this for the actual values reference.

<?php

echo JSON_ERROR_NONE . ' JSON_ERROR_NONE' . '<br />';
echo
JSON_ERROR_DEPTH . ' JSON_ERROR_DEPTH' . '<br />';
echo
JSON_ERROR_STATE_MISMATCH . ' JSON_ERROR_STATE_MISMATCH' . '<br />';
echo
JSON_ERROR_CTRL_CHAR . ' JSON_ERROR_CTRL_CHAR' . '<br />';
echo
JSON_ERROR_SYNTAX . ' JSON_ERROR_SYNTAX' . '<br />';
echo
JSON_ERROR_UTF8 . ' JSON_ERROR_UTF8' . '<br />';
echo
JSON_ERROR_RECURSION . ' JSON_ERROR_RECURSION' . '<br />';
echo
JSON_ERROR_INF_OR_NAN . ' JSON_ERROR_INF_OR_NAN' . '<br />';
echo
JSON_ERROR_UNSUPPORTED_TYPE . ' JSON_ERROR_UNSUPPORTED_TYPE' . '<br />';

/*
The above outputs :
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
6 JSON_ERROR_RECURSION
7 JSON_ERROR_INF_OR_NAN
8 JSON_ERROR_UNSUPPORTED_TYPE
*/

?>
hemono at gmail dot com 18-Oct-2015 03:02
when json_decode a empty string, PHP7 will trigger an Syntax error:
<?php
json_decode
("");
var_dump(json_last_error(), json_last_error_msg());

// PHP 7
int(4)
string(12) "Syntax error"

//  PHP 5
int(0)
string(8) "No error"
praveenscience at gmail dot com 21-Oct-2014 03:17
I used this simple script, flicked from StackOverflow to escape from the function failing:

<?php
   
function utf8ize($d) {
        if (
is_array($d)) {
            foreach (
$d as $k => $v) {
               
$d[$k] = utf8ize($v);
            }
        } else if (
is_string ($d)) {
            return
utf8_encode($d);
        }
        return
$d;
    }
?>

Cheers,
Praveen Kumar!
williamprogphp at yahoo dot com dot br 30-Jan-2014 06:32
This is a quite simple and functional trick to validate JSON's strings.

<?php

   
function json_validate($string) {
        if (
is_string($string)) {
            @
json_decode($string);
            return (
json_last_error() === JSON_ERROR_NONE);
        }
        return
false;
    }
    echo (
json_validate('{"test": "valid JSON"}')  ? "It's a JSON" : "NOT is a JSON"); // prints 'It's a JSON'
   
echo (json_validate('{test: valid JSON}')  ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to missing quotes
   
echo (json_validate(array())  ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to a non-string argument
?>

Cheers
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.
PHP8中文手册 站长在线 整理 版权归PHP文档组所有