JSON——從網路到 Python
太棒了,恭喜你!你剛剛用 Python 以程式方式查詢了第一個 API,並把回應文字列印到終端機。不過,如同你所知,回應其實是 JSON,所以你可以更進一步把 JSON 解碼。接著你就能列印出轉換後字典的鍵值配對。現在就來完成這一步吧!
本練習屬於課程
Python 資料匯入進階
練習說明
- 將變數
url傳入requests.get()函式以送出相關請求並接住回應,並把得到的回應物件指定給變數r。 - 對回應物件
r套用json()方法,並將得到的字典儲存到變數json_data。 - 按下 送出答案,把字典
json_data的鍵值配對列印到終端機。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import package
import requests
# Assign URL to variable: url
url = 'http://www.omdbapi.com/?apikey=72bc447a&t=social+network'
# Package the request, send the request and catch the response: r
# Decode the JSON data into a dictionary: json_data
# Print each key-value pair in json_data
for k in json_data.keys():
print(k + ': ', json_data[k])