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 为什么eprime输出的数据会有缺失?
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题