Jhay
Jhay

Reputation: 77

Laravel PHP JSON Decoding

I have a code which looks like 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 from a database, the only problem I've got is that, I can't decode it using json_decode... Are there any class or function that can decode this to convert into array()?

Upvotes: 0

Views: 3671

Answers (1)

Quasdunk
Quasdunk

Reputation: 15220

As already mentioned in my comment, what you have there is a whole HTTP response. It holds the JSON data in the body, so you need to parse that. Here's one way to go about it:

preg_match("/\{(.*)\}/s", $rawResponse, $matches);

This matches everything between the firs "{" and the last "}", which is where the JSON data lives, and stores every match in $matches. Since there should only be one match, we're interested in $matches[0].

Now you only need to decode it back:

$data = json_decode($matches[0]);

// or 
// $data = json_decode($matches[0], true) 
// if you want an associative array instead of an object.

Caveat: This won't work with your example, because it's not valid JSON. The comma after "online_status": 1, makes it invalid so json_decode will return false. But I guess you just stripped some lines in your question for better readability.

If you have control over how things are stored, you should definitely consider only storing the JSON data so you wouldn't have to deal with such issues. If you still somehow need the whole raw response, maybe store it in another table / column. This makes things a lot easier, especially with Laravel. For instance, if the data is something like a details field on a Transaction model or something, you could do someting like this:

class Transaction extends Model {

    protected $casts = [
        'details' => 'json'
    ];

}

Now, when accessing $transaction->details you'll automatically get an array. And this even works in both directions: $transaction->details = ['new' => 'data'] will convert it to JSON before saving it. So you wouldn't have to deal with converting back and forth at all.

Upvotes: 1

Related Questions