开发者

Make Json parsable by php

开发者 https://www.devze.com 2023-04-01 05:20 出处:网络
I have some weirdly formatted json string which is invalid json, but executes as valid javascript. This means PHP json_decode, will not work.

I have some weirdly formatted json string which is invalid json, but executes as valid javascript. This means PHP json_decode, will not work.

{
  "Devices":{
    "Device1":"{ \"Name\"=\>\"AutoTap LDVDS\",\"ID\"=\>\"LDVDSDevice\"}"
  }
}

The backslashes are not valid. Is there some way I can escape this string so it can be re-encoded exactly the same as it came in?

Edit I don't care about parsing the messy string at all. It's preventing me from accessing other data. I was doing a simple regex to strip the ugly strings out of the json before parsing it. But now I need to re-encode the result array back into JSON and I want to avoid losing this data. The ugly string should remain exactly the same, as it may be 开发者_StackOverflowimportant to some other application that uses this data.

The => comes from ruby object notation in case you are wondering.


Well, it's those weird escaped > that are killing it: \>

I see no reason why you can't str_replace them out of existence safely with a simple:

<?php

$code='{
  "Devices":{
    "Device1":"{ \"Name\"=\>\"AutoTap LDVDS\",\"ID\"=\>\"LDVDSDevice\"}"
  }
}';

$code=str_replace('\\>','>',$code);

var_export(json_decode($code));

But then, you know the domain of your data.
And you should apply a grain of salt before applying that blindly to all your inputs.


You could run stripslashes on it, and then pass that sring into json_decode.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号