我在通过 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 manual用于错误代码识别
关于javascript - PHP json_decode 无法解析 JS JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32098338/