php 解析json失败,解析为空,json在线解析器可以解析,但是json_decode()解析失败(原)

$str2='{"code":200,"datas":{"id":1,"coupon_id":"123","validity":"2018-08-14","is_use":0,"source":"2","create_time":"2018-08-14 15:06:40"}}';
var_dump(json_decode($str2));  //输出为 NULL 

json在线解析器去掉两边单引号是可以解析的

但是实际代码运行,不论是直接json_decode()还是去掉两边单引号都无法解析.

造成这种问题的源头就是bom头,返回的结果是带bom头的utf8格式的数据,因此只要去除bom头就好了,添加一个方法:

function clearBom($str){
   $bom = chr(239).chr(187).chr(191); 
   return str_replace($bom ,'',$str);     
}

 然后问题就解决了

$str2='{"code":200,"datas":{"id":1,"coupon_id":"123","validity":"2018-08-14","is_use":0,"source":"2","create_time":"2018-08-14 15:06:40"}}';
var_dump(json_decode(clearBom($str2)));
 
结果如下:
object(stdClass)#1 (2) {
  ["code"]=>
  int(200)
  ["datas"]=>
  object(stdClass)#2 (6) {
    ["id"]=>
    int(1)
    ["coupon_id"]=>
    string(3) "123"
    ["validity"]=>
    string(10) "2018-08-14"
    ["is_use"]=>
    int(0)
    ["source"]=>
    string(1) "2"
    ["create_time"]=>
    string(19) "2018-08-14 15:06:40"
  }
}

 

posted @ 2019-08-29 14:25  戈丫汝  阅读(3044)  评论(1编辑  收藏  举报