Laravel PHP JSON Decoding -
i have code looks this
""" http/1.0 200 ok\r\n cache-control: no-cache\r\n content-type: application/json\r\n date: tue, 08 nov 2002 05:46:42 gmt\r\n \r\n {\n "request": {\n "body": ""\n },\n "response": {\n "status": 1,\n "users": [\n {\n "user_id": 1,\n "username": "john.doe",\n "account_status": "1",\n "online_status": 1,\n } ]\n }\n } """
that value came database, problem i've got that, can't decode using json_decode... there class or function can decode convert array()?
as mentioned in comment, have there whole http response. holds json data in body, need parse that. here's 1 way go it:
preg_match("/\{(.*)\}/s", $rawresponse, $matches);
this matches between firs "{" , last "}", json data lives, , stores every match in $matches
. since there should 1 match, we're interested in $matches[0]
.
now need decode back:
$data = json_decode($matches[0]); // or // $data = json_decode($matches[0], true) // if want associative array instead of object.
caveat: won't work example, because it's not valid json. comma after "online_status": 1,
makes invalid json_decode
return false
. guess stripped lines in question better readability.
if have control on how things stored, should consider storing json data wouldn't have deal such issues. if still somehow need whole raw response, maybe store in table / column. makes things a lot easier, laravel. instance, if data details
field on transaction
model or something, someting this:
class transaction extends model { protected $casts = [ 'details' => 'json' ]; }
now, when accessing $transaction->details
you'll automatically array. , works in both directions: $transaction->details = ['new' => 'data']
convert json before saving it. wouldn't have deal converting , forth @ all.
Comments
Post a Comment