繁体   English   中英

PHP无法解析JS JSON json_decode

[英]JS JSON not parsed by PHP json_decode

我在通过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 );

格式错误的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手册中的错误代码识别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM