json_decode 打印 null

                                                                   json_decode 打印 null

1、json_last_error() 方法找出错误原因。

$str = '{"aa":}';
$r = json_decode($str);
echo json_last_error();
die;

//打印 4

   json_last_error() 报错int(3)的解决办法

解析前 使用以下代码:
$result =  preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($result));

2、json_last_error()错误msg对照表

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

3、或者使用方法:json_last_error_msg()

$str = '{"aa":}';
$r = json_decode($str);
echo json_last_error_msg();
die;

打印:unexpected character

4、其他原因

1.$str只能UTF-8编码
2.元素最后不能有逗号(与php的array不同)
3.元素不能使用单引号
4.元素值中间不能有空格和/n,必须替换。

参考地址:json_decode()值等NULL空用json_last_error()判断的解决办法

猜你喜欢

转载自blog.csdn.net/qq_36025814/article/details/87271096