2016-12-06 62 views
0

我正在處理請求,並且我被困住了,因爲我正在更改我的源代碼。事情是,當我請求對象的網站,它返回以下JSON對象:如何解析這個json對象到Python?

[ 
{ 
"directory":"ca\/48", 
"hash":"ca4860af9e3be43b1d23b823af607be4", 
"height":1839, 
"id":3461818, 
"image":"ca4860af9e3be43b1d23b823af607be4.jpg", 
"change":1480968006, 
"owner":"danbooru", 
"parent_id":null, 
"rating":"s", 
"sample":true, 
"sample_height":1398, 
"sample_width":850, 
"score":0, 
"tags":"1girl breasts cape cleavage defense_of_the_ancients dota_2 green_eyes highres lyralei medium_breasts parted_lips pauldrons red_hair smile solo splashbrush thick_thighs thighs toes", 
"width":1118, 
"file_url":"http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg" 
} 
] 

我想從"http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg"

"file_url"值更改爲

​​ 所以我通過在我的程序構建器上調用它可以完全使用該網站。 我該怎麼做? 在此先感謝。

+0

可能有數百個類似的問題。請在發佈可能是重複的內容之前進行一些調查。 –

+0

「json對象」在Python中不太重要。你有一個單一的項目,這是一個字典。如果你知道如何修改一個字典並訪問一個列表元素,你會發現其餘的。 – bereal

+0

'requests'可以將JSON轉換爲python dictionary/list - 'response.json' - 它可以將'\ /'轉換爲正確的文本。 – furas

回答

1

requests可以JSON數據自動轉換到Python字典/列表

r = request.get(...) 

data = r.json() 

,然後你有機會

print(data[0]['file_url']) 

,你會看到,有沒有\/因爲它轉化爲正確的文本。


實施例與用於由requests內部標準json模塊。

text = '''[ 
{ 
"directory":"ca\/48", 
"hash":"ca4860af9e3be43b1d23b823af607be4", 
"height":1839, 
"id":3461818, 
"image":"ca4860af9e3be43b1d23b823af607be4.jpg", 
"change":1480968006, 
"owner":"danbooru", 
"parent_id":null, 
"rating":"s", 
"sample":true, 
"sample_height":1398, 
"sample_width":850, 
"score":0, 
"tags":"1girl breasts cape cleavage defense_of_the_ancients dota_2 green_eyes highres lyralei medium_breasts parted_lips pauldrons red_hair smile solo splashbrush thick_thighs thighs toes", 
"width":1118, 
"file_url":"http:\/\/gelbooru.com\/images\/ca\/48\/ca4860af9e3be43b1d23b823af607be4.jpg" 
} 
]''' 

import json 

data = json.loads(text) 

print(data[0]['file_url'])