2015-10-28 42 views
0

我從請求調用中返回一個JSON對象。我想從它獲得所有的值並將它們存儲在一個平面陣列中。從一個JSON對象中獲取所有的值並將它們存儲在一個Python平面數組中

我的JSON對象:

[ 
    { 
     "link": "https://f.com/1" 
    }, 
    { 
     "link": "https://f.com/2" 
    }, 
    { 
     "link": "https://f.com/3" 
    } 
] 

我想存儲該爲:

[https://f.com/things/1, https://f.com/things/2, https://f.com/things/3] 

我的代碼如下..它只是打印出每一個環節出:

import requests 
    import json 

def start_urls_data(): 
    url = 'http://106309.n.com:3000/api/v1/product_urls?q%5Bcompany_in%5D%5B%5D=F' 
    headers = {'X-Api-Key': '1', 'Content-Type': 'application/json'} 
    r = requests.get(url, headers=headers) 
    start_urls_data = json.loads(r.content) 
    for i in start_urls_data: 
     print i['link'] 

回答

2

你可以使用一個簡單的列表理解:

data = [ 
    { 
     "link": "https://f.com/1" 
    }, 
    { 
     "link": "https://f.com/2" 
    }, 
    { 
     "link": "https://f.com/3" 
    } 
] 

print([x["link"] for x in data]) 

此代碼只是循環遍歷列表data,並將密鑰link的值從dict元素置於新列表中。

相關問題