2017-06-15 34 views
0

有一個基本的URL,我想添加列表值等,使我有URL列表刮。我的列表來自一個JSON文件,看起來像:我如何列表值附加到URL在Python

[{u'url': [u'/location/subfile/file1.htm', u'/location/subfile/file2.htm', u'/location/subfile/file3.htm', u'/location/subfile/file4.htm']}] 

我的基本URL是一樣的東西http://example.com/placeforfiles/

我想要什麼,最終是有一個基礎URL加上列表值的URL集合,像這樣:

http://example.com/placeforfiles/location/subfile/file1.htm 
http://example.com/placeforfiles/location/subfile/file2.htm 
http://example.com/placeforfiles/location/subfile/file3.htm 
http://example.com/placeforfiles/location/subfile/file4.htm 

可能有成千上萬,我需要追加列表值的,所以我知道我需要遍歷,並將其附加,但我還沒有找到一個可行的解決方案。目前,我想要:

import json 

with open ('returned_items.json') as links: 
    data = json.load(links) 

base_url = 'http://example.com/placeforfiles/{}' 

for i in data: 
    url = 'http://example.com/placeforfiles/{}'.format(i) 
    print url 

這是返回:

http://example.com/placeforfiles/({u'url': [u'/location/subfile/file1.htm', u'/location/subfile/file2.htm', u'/location/subfile/file3.htm', u'/location/subfile/file4.htm']},) 
+0

對不起,只是意識到這是在那裏偶然我編輯的問題,將其刪除。 –

回答

1

這是因爲字典是數組中的第一個元素。 循環應該是for i in data[0]["url"]

1
#replcace data with below line 
data = json.loads(links) 

#replace your last loop with below 
if data and 'url' in data[0]: 
for i in data[0]['url']: 
    url = 'http://example.com/placeforfiles{}'.format(i) 
    print(url)