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("/ /", " ", $ret); //$jsonstr = preg_replace("/ /", ' ', $jsonstr); $jsonstr = str_replace(" ", ' ', $jsonstr); //print_r($jsonstr);exit; //$jsonstr = str_replace (' ','', $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