您好,欢迎来到叨叨游戏网。
搜索
您的当前位置:首页php使用json_decode返回NULL

php使用json_decode返回NULL

来源:叨叨游戏网

php5.2以后自带json_decode函数,但是对json文本串的格式要求非常严格。

很可能使用该函数得到的返回值是NULL

可以使用使用json_last_error()函数获取到的返回值来帮助我们判断出问题的原因。

其中如果提示错误JSON_ERROR_SYNTAX(Syntax error),表示json串格式错误。

可以通过以下几个方式排错:

1. json字符串必须以双引号包含

$output = str_replace("'", '"', $output);

2. json字符串必须是utf8编码
$output = iconv('gbk', 'utf8', $output);

3.不能有多余的逗号 如:[1,2,]
用正则替换掉,preg_replace('/,\s*([\]}])/m', '$1', $output)

4、不能有换行、制表符:

$jsonstr = '
{"succ":true,"data":{"id":"31","keywords":"","description":"","jianjie":"       ","jianjie_short":"bb","nav":"ccc","deleted":"0","url":"http:\/\/travel.sina.com.cn\/beijing\/
"}}';

//$ret=preg_replace("/\t/", " ", $ret);  
//$jsonstr = preg_replace("/\n/", ' ', $jsonstr);
$jsonstr = str_replace("\n", ' ', $jsonstr);
//print_r($jsonstr);exit;
//$jsonstr = str_replace ('\n','', $jsonstr);
$jd = json_decode($jsonstr,true);

$errorinfo = json_last_error();
echo $errorinfo;  //错误信息会在客户端的页面显示,错误代码如下0-5
//print_r(JSON_ERROR_DEPTH);
print_r($jd);

0 = JSON_ERROR_NONE                                  没有错误发生
1 = JSON_ERROR_DEPTH                                超过了最大堆栈深度
2 = JSON_ERROR_STATE_MISMATCH           无效的或者是有缺陷的json
3 = JSON_ERROR_CTRL_CHAR                      发生控制特性错误,可能是有误的编码
4 = JSON_ERROR_SYNTAX                               发生语法错误
5 = JSON_ERROR_UTF8Malformed UTF-8    有缺陷的UTF-8编码特性,也可能是有误的编码   PHP 5.3.3


因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- gamedaodao.net 版权所有 湘ICP备2024080961号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务