[英]Couldn't convert string to JSON. String to Valid JSON and parse the JSON in PHP
I am having the following JSON(invalid) as a string. 我将以下JSON(无效)作为字符串。 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. 结果
$newjson
不作为JSON对象返回,它仅作为字符串给出。
I need JSON object not a string. 我需要JSON对象而不是字符串。
In the given JSON, json
value is a string(inside valid JSON) which starts with "
. 在给定的JSON中,
json
值是一个以"
开头的字符串(在有效JSON内)。
I need to remove this. 我需要删除它。
json_encode
takes a PHP data structure and turns it into a string of JSON. json_encode
采用PHP数据结构,并将其转换为JSON字符串。
You need json_decode
to go the other way. 您需要使用
json_decode
进行其他操作。
The string is mostly valid json, you just need to tweak a few things: 该字符串主要是有效的json,您只需要进行一些调整:
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. 一旦完成,我就能够成功解码您的json。 This could possibly be done faster with preg_replace, but I suck at regexes.
可以使用preg_replace更快地完成此操作,但是我对正则表达式感到厌烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.