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 依据报错在原代吗格式的基础上解决问题
  • ¥15 在虚拟机中安装flash code
  • ¥15 单片机stm32f10x编写光敏电阻调节3.3伏大功率灯亮度(光强越大灯越暗,白天正常光强灯不亮,使用ADC,PWM等模块)望各位找一下错误或者提供一个可实现功能的代码
  • ¥20 verilog状态机方法流水灯
  • ¥15 pandas代码实现不了意图
  • ¥15 GD32H7 从存储器到外设SPI传输数据无法重复启用DMA
  • ¥25 LT码在高斯信道下的误码率仿真
  • ¥45 渲染完成之后将物体的材质贴图改变,自动化进行这个操作
  • ¥15 yolov5目标检测并显示目标出现的时间或视频帧
  • ¥15 电视版的优酷可以设置电影连续播放吗?