douguaidian8021 2015-08-19 14:28 采纳率: 100%
浏览 146
已采纳

JS JSON没有被PHP json_decode解析

I have an issue with parsing JSON data by json_decode PHP function. The issue is that the JSON I receive is not properly formatted. 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. Is it possible to properly format this string with a preg_replace function

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.

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

1条回答 默认 最新

  • doqvzh345334 2015-08-19 14:35
    关注

    Working solution for your malformed 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
    ]*(\w+)[ ]*:[ ]*/','$1"$2":',$json);
    $json = preg_replace('/":\'?([^\[\]\{\}]*?)\'?[ 
    \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. 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. Check the php manual for error codes identification

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog