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=strreplace("",", output);

  1. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值