2016-10-19 79 views
0

我得到以下JSON響應,當我查詢我的數據庫:防止JSON編碼從返回數組作爲字符串

[{"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\"}]"}] 

它是所有除了products值是一個字符串,它應該是一個數組好。

我正在使用Laravel 5.3作爲我的框架,但我不認爲這有所作爲。

我可以以某種方式強制它返回數組作爲數組而不是字符串?

+5

了'products'值看起來雙JSON編碼。你能包含生成這個JSON的代碼嗎? –

+0

這是一個laravel查詢,DB :: table('orders') - > get();在數據庫中的列是這樣的:[{「count」:2,「id」:1,「price」:275,「name」:「Kayak」},{「count」:1,「id」 2,「price」:48​​.95,「name」:「Lifejacket」}] – frc

+0

它以JSON格式保存在數據庫中? –

回答

2

在主串你的產品也是JSON字符串編碼的數據,因此,所有你需要做的解碼是

$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); 

這將返回

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 
         ) 

       ) 

     ) 

)