2015-10-28 43 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元素置于新列表中。

相关问题