天天看點

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();

//print_r(JSON_ERROR_DEPTH);

print_r($jd);

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

0 = JSON_ERROR_NONE No 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_CHAR Control character error, possibly incorrectly encoded  

4 = JSON_ERROR_SYNTAX Syntax error  

5 = JSON_ERROR_UTF8 Malformed UTF-8 characters, possibly incorrectly encoded PHP 5.3.3