JS JSON没有被PHP json_decode解析

时间:2015-08-19 14:28:16

标签: javascript php json

我有一个通过json_decode PHP函数解析JSON数据的问题。问题是我收到的JSON格式不正确。它看起来如下:

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

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

修改 我在网上找到了这个代码,但它只包含引号中的变量名。这些值仍然是原样,json_decode仍然返回NULL。

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

1 个答案:

答案 0 :(得分:1)

畸形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\n]*(\w+)[ ]*:[ ]*/','$1"$2":',$json);
$json = preg_replace('/":\'?([^\[\]\{\}]*?)\'?[ \n\t]*(,"|\}$|\]$|\}\]|\]\}|\}|\])/','":"$1"$2',$json);

var_dump($json);

var_dump(json_decode($json));

但一般来说,你需要用双引号"arg":1包装对象参数。非数字值也。就像这样:

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

第二个函数返回错误的id,如果有的话。 检查php manual是否有错误代码识别