drhzn3911 2017-09-01 11:20
浏览 119
已采纳

无法将字符串转换为JSON。 字符串到有效JSON并在PHP中解析JSON

I am having the following JSON(invalid) as a string. I need to parse it and get the inner value. I tried a lot but didn't get the result.

    $sJson = '{"Place":"MyStore","PurchaseID":"IND.1234-5678-9012-34567","details":"{\"json\":\"{\\\"PurchaseID\\\":\\\"IND.1234-5678-9012-34567\\\",\\\"categoryname\\\":\\\"smartpack\\\",\\\"productname\\\":\\\"bitcoinpack1\\\",\\\"purchaseTime\\\":1504256011148,\\\"purchaseState\\\":\\\"Success\\\",\\\"UniqueToken\\\":\\\"jbbefjifdkpdpajfkomckoof.AO-J1OzEdsZX17M5pAvedDh1Ep_WwlOKamMQN_3O89bRbAPX-uoqPpTJf8EdNcjMhCK1dptGaWReUCSS9JGCJuh6GlAT0l11mkUddo_uJ4YOe8ezYxlmDQ8\\\"}\",\"currentvalue\":\"S270U2J3XF\\/+XnC1ocPp0d\\/Kwf\\/4B\\/\\/tT7urbDn6F+\\/D8j7VD1t8qqwevtKDnAafAtvocPg4Eevkf\\/GZKl1YOgUYyuY63nyekz7GRDuIKVXAZ+iZtPAbwCuwZplUQHaVA\\/EBMjYpPQM0EFtp2WuX\\/Tx9nTnFCtU+gAK4Rg0zLvQNKSJx5WfqhK7wf0wHTTYviTkB\\/pETnkV22oQDIZH9\\/Fy1FXltC7FXHXoMcxtGvkgPSEFOnms4HumjUQ5PtQUbxh\\/oirQeROCAhkO+WKX9WO3bCKjru1uuxspTLCNGJEKAezi2GEBcpFGjq4iS5N7SfO5BOF76\\/joLe3B7OemJNw==\"}"}';

    $sJson = json_encode($sJson,JSON_UNESCAPED_SLASHES);
    $json_array = (array) json_decode($sJson,true);
    $newjson=preg_replace('/.+?({.+}).+/','$1',$json_array);
    var_dump($newjson);
    exit;

The Result $newjson is not return as JSON Object, it gives as only string.

I need JSON object not a string.

In the given JSON, json value is a string(inside valid JSON) which starts with ".

I need to remove this.

  • 写回答

2条回答 默认 最新

  • doujiunai2169 2017-09-01 11:36
    关注

    The string is mostly valid json, you just need to tweak a few things:

    First, replace all of the \\" with ". (I had to run this twice)

    $string = str_replace('\\"', '"', $string);
    

    Then some of the braces are quoted:

    $string = str_replace('"{', '{', $string);
    $string = str_replace('}"', '}', $string);
    

    Once that was done, I was able to successfully decode your json. This could possibly be done faster with preg_replace, but I suck at regexes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 全志H618ROM新增分区
  • ¥20 jupyter保存图像功能的实现
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况