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

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

图片转代码服务由CSDN问答提供 功能建议

我在使用json_decode PHP函数解析JSON数据时遇到问题。 问题是我收到的JSON格式不正确。 它看起来如下:

 “{user:1,product:4,commentCount:1,comment:'一切都很好!干得好。'  ,commentDate:{year:2015,month:8,day:19},赞:8}“
   
 
 

当我尝试使用json_decode PHP函数解码此字符串时 我得到NULL。 是否可以使用preg_replace函数正确格式化此字符串

编辑: 我在网上找到了这段代码,但它只包装了 引号中的变量名。 这些值仍然是原样,json_decode仍然返回NULL。

  //修复变量名
 $ 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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题