javascript - PHP json_decode 无法解析 JS JSON

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

最佳答案

针对格式错误的 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/

相关文章:

c# - Teamcity - 编写访问单独 JSON 文件的测试

javascript - 未捕获的语法错误 : Unexpected end of input Google Charts

javascript - vuejs方法中的Parseint

php - 将 3 列(日、月、年)转换为 PHP 日期/时间戳

php - xml php mysql utf-8 : Greek chars dont display correct in xml

ios - Swift 如何更新(修改、删除、添加)JSON 条目

javascript - Typeahead 并未显示 json 中的所有项目

javascript - 在 javascript 中使用严格不适用于粗箭头?

javascript - 使用 HTML/Javascript 在表单文本框中显示单选按钮的值

php - 如何用预言测试 Doctrine Entity Manager findOneById 方法?