douguaidian8021 2015-08-19 14:28 采纳率: 100%
浏览 146
已采纳

JS JSON没有被PHP json_decode解析

I have an issue with parsing JSON data by json_decode PHP function. The issue is that the JSON I receive is not properly formatted. It looks as follows:

"{ user:1 ,product:4 ,commentCount: 1 ,comment:'All fine! Well done.' ,commentDate:{ year:2015 ,month:8 ,day:19 } , likes:8 }"

When I try to decode this string with json_decode PHP function I get NULL. Is it possible to properly format this string with a preg_replace function

EDIT: I found this code on the web but it only wraps the variable names in the quotes. The values are still as they were and json_decode still returns NULL.

// fix variable names
$PHPJSON = preg_replace( '/([a-zA-Z0-9_]+?):/' , '"$1":', $PHPJSON );
  • 写回答

1条回答 默认 最新

  • doqvzh345334 2015-08-19 14:35
    关注

    Working solution for your malformed json:

    $json = "{ user:1 ,product:4 ,commentCount: 1 ,comment:'All fine! Well done.' ,commentDate:{ year:2015 ,month:8 ,day:19 } , likes:8 }";
    
    $json = preg_replace('/(,|\{)[ \t
    ]*(\w+)[ ]*:[ ]*/','$1"$2":',$json);
    $json = preg_replace('/":\'?([^\[\]\{\}]*?)\'?[ 
    \t]*(,"|\}$|\]$|\}\]|\]\}|\}|\])/','":"$1"$2',$json);
    
    var_dump($json);
    
    var_dump(json_decode($json));
    

    But in general you need to wrap object param in double quotes "arg":1. Non-numeric values also. Just like this:

    var_dump(json_decode('{"user":1}'));
    var_dump(json_last_error());
    

    The second function returns you id of an error, if there was any. Check the php manual for error codes identification

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?