在PHP中解码无效的JSON

时间:2017-02-20 09:47:00

标签: php json

我从外部源获得了无效的JSON返回,看起来像这样

USER SAVED IN DB.{"user":{"_token":"9ylCAviuuCaNlCtXNya5pEXkY8vkJepZAohsG5VI","submit":"engageiq_post_data","affiliate_id":"","campaign_id":"","offer_id":"","s1":"","s2":"","s3":"","s4":"","s5":"","address":"","phone1":"","phone2":"","phone3":"","phone":"","source_url":"http:\/\/pfr_laravel.dev\/registration","ip":"192.168.10.1","screen_view":"1","first_name":"fff","last_name":"ff","email":"r@yahoo.com","zip":"00501","birthdate":"","dobmonth":"04","dobday":"12","dobyear":"1965","gender":"M","chk_agree":"","submitBtn":"Submit","state":"NY","city":"Holtsville","revenue_tracker_id":1},"revenue_tracker_id":1,"path_type":2,"campaigns":[[1,15,25,48,38,23,44],[245],[249],[27,4,19,181,18],[16],[246],[51,52,151],[10],[26,2,185,180,45,184,182]],"creatives":[]}

如果我尝试解码

,这将返回null
json_decode($myjson, true)

我只想要path_type键及其值

所以在我的代码中我需要这个

if (path_type == 2){}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

扩展@ MrDarkLynx的回答我使用这个正则表达式: ^(.+?){"user" 使用该正则表达式删除{"user"之前的所有内容,请务必仅删除第一个捕获的组。

您现在可以使用有效的JSON =)

答案 1 :(得分:0)

首先,您要从JSON中删除不必要的字符串 然后,您希望将已解码的JSON存储在变量中并检查路径类型:

$myjson = substr($myjson, 17); // remove bulk from JSON

$data = json_decode($myjson, true);

if ($data['path_type'] == 2) {
    // code
}