修复PHP支持的标准JSON数据格式

时间:2022-08-17 19:01:44

PHP的json_decode无法解析的JSON数据,代码如下:

 
 
  1. $json = "{rst:5,c:[ [1018485,2,0,0,0,0,'','0-0','','',2,0,2],[1049809,17,0,0,0,0,'','','','',1,0,1],[1049813,17,0,0,0,0,'','','','',1,0,1],[1049810,17,0,0,0,0,'','','','',1,0,1]],fn:135388}";
  2. echo json_decode($json);

//结果输出: null

存在的问题:

      1. Value没有使用双引号括起,而是使用了单引号

      2. Key没有被双引号括起

修复代码:

 
 
  1. preg_replace('@([\w_0-9]+):@', '"\1":', str_replace('\'', '"', $json));

执行后的结果:

 
 
  1. echo $json;
  2. {"rst":5,"c":[ [1018485,2,0,0,0,0,"","0-0","","",2,0,2],[1049809,17,0,0,0,0,"","","","",1,0,1],[1049813,17,0,0,0,0,"","","","",1,0,1],[1049810,17,0,0,0,0,"","","","",1,0,1]],"fn":135388}