frc frc - 1 month ago 7
JSON Question

prevent json encode from returning arrays as strings

I get the following json response when I query my database:

[{"id":1,"name":"my name","street":"Sava Burica","city":"Belgrade","state":"Zemun","zip":"11080","country":"Serbia","giftwrap":null,"products":"[{\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},{\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}]"}]


It is all good except that the
products
value is a string and it should be an array.

I am using Laravel 5.3 as my framework but I don't think that makes a difference.

Can I somehow force it to return arrays as arrays and not as strings?

Answer

In the main string your products is also JSON String encoded data, so all you need to do to decode it is

$s = '[{"id":1,"name":"my name","street":"Sava Burica","city":"Belgrade","state":"Zemun","zip":"11080","country":"Serbia","giftwrap":null,"products":"[{\"count\":2,\"id\":1,\"price\":275,\"name\":\"Kayak\"},{\"count\":1,\"id\":2,\"price\":48.95,\"name\":\"Lifejacket\"}]"}]';
$address = json_decode($s,true);

$s = $address[0]['products'];
$address[0]['products'] = json_decode($s,true);
print_r($address);

This returns

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => my name
            [street] => Sava Burica
            [city] => Belgrade
            [state] => Zemun
            [zip] => 11080
            [country] => Serbia
            [giftwrap] => 
            [products] => Array
                (
                    [0] => Array
                        (
                            [count] => 2
                            [id] => 1
                            [price] => 275
                            [name] => Kayak
                        )

                    [1] => Array
                        (
                            [count] => 1
                            [id] => 2
                            [price] => 48.95
                            [name] => Lifejacket
                        )

                )

        )

)
Comments