php使用json_decode返回NULL

来源:互联网 发布:linux基础入门ppt 编辑:程序博客网 时间:2024/05/17 23:26

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();
//print_r(JSON_ERROR_DEPTH);
print_r($jd);

//-------------------------------------------------

0 = JSON_ERROR_NONENo error has occurred 

1 = JSON_ERROR_DEPTH The maximum stack depth has been exceeded 

2 = JSON_ERROR_STATE_MISMATCH   Invalid or malformed JSON 

3 = JSON_ERROR_CTRL_CHARControl character error, possibly incorrectly encoded 

4 = JSON_ERROR_SYNTAXSyntax error 

5 = JSON_ERROR_UTF8Malformed UTF-8 characters, possibly incorrectly encodedPHP 5.3.3