简体   繁体   English

PHP无法解析JS JSON json_decode

[英]JS JSON not parsed by PHP json_decode

I have an issue with parsing JSON data by json_decode PHP function. 我在通过json_decode PHP函数解析JSON数据时遇到问题。 The issue is that the JSON I receive is not properly formatted. 问题是我收到的JSON格式不正确。 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. 当我尝试使用json_decode PHP函数解码此字符串时,我得到NULL。 Is it possible to properly format this string with a preg_replace function 是否可以使用preg_replace函数正确格式化此字符串

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. 这些值仍然保持不变,并且json_decode仍返回NULL。

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

Working solution for your malformed json: 格式错误的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));

But in general you need to wrap object param in double quotes "arg":1 . 但通常,您需要将对象参数包装在双引号"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. 第二个函数返回您的错误ID(如果有)。 Check the php manual for error codes identification 检查php手册中的错误代码识别

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

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