Ian Adem
Ian Adem

Reputation: 119

Decode invalid JSON in PHP

I have an invalid JSON return from external source that looks like this

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":"[email protected]","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":[]}

This would return null if I am trying to decode

json_decode($myjson, true)

I only want the path_type key and its value

So in my code I would need this

if (path_type == 2){}

Any ideas?

Upvotes: 1

Views: 386

Answers (2)

JordyvD
JordyvD

Reputation: 1615

Expanding on @MrDarkLynx's answer I'd use this regex: ^(.+?){"user" Use that regex to remove everything before {"user", be sure to only remove the first captured group.

You'll now have valid JSON you can use =)

Upvotes: 1

MrDarkLynx
MrDarkLynx

Reputation: 686

First you want to strip the unnecessary string from your JSON.
Then you want to store the decoded JSON in a variable and check the path type:

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

$data = json_decode($myjson, true);

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

Upvotes: 0

Related Questions