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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办