json_decode()值等NULL空用json_last_error()判断的解决办法

$data = json_decode($json_string, true );

值等null空时,

用son_last_error()来判断是哪方面出错

$data = json_decode($json_string, true );
							
if(!$data)
{
        //error handle ,错误处理
        $ret = json_last_error();
        print_r($ret);   //打印为: 4,查错误信息表,可知是语法错误
        
}   

 

其它的json_decode($str)返回NULL的一些原因:

1.$str只能UTF-8编码

2.元素最后不能有逗号(与php的array不同)

3.元素不能使用单引号

4.元素值中间不能有空格和n,必须替换

 

json_last_error错误msg对照表:

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

 

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

解决方法: 
解析前 使用以下代码:

$result =  preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($result));

例子:

$json_string =  preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($json_string));
$data = json_decode($json_string, true );
							
if(!$data)
{
        //error handle ,错误处理
        $ret = json_last_error();
        print_r($ret);   //打印为: 4,查错误信息表,可知是语法错误
        
}   

 

引用:

https://blog.csdn.net/qq_38083665/article/details/80707227

https://segmentfault.com/a/1190000006154011

https://www.cnblogs.com/jamesbd/p/4185342.html

 

 

 

你可能感兴趣的:(php,thinkphp5)