2017-02-26 90 views
1

我正在使用JSON作爲FAA的API。對於我的下面的代碼,我試圖將「airport_response」變量中的獲取數據打印到名爲「airport_data」的字典中。然後我只想打印出名爲airport_data_keys的密鑰。目前,我得到一個不正確的值,序列元素#0的長度是128,但是2是必需的。任何幫助,將不勝感激。API查詢,JSON,字典

import json 
import requests 
url_parameters = {} 
url_parameters["format"] = "json" 
base_url = 'http://services.faa.gov/airport/status/' 
airport = 'DTW' 
airport_response = requests.get(base_url + airport, params = url_parameters) 
airport_data = airport_response.json() 
airport_data = dict(airport_response) 
for k, v in airport_data.items(): 
    k = airport_data_keys 
    print airport_data_keys 

電流輸出:

狀態 城市 名稱 IATA ICAO 狀態 延遲 天氣

期望的輸出:[u'status',u'ICAO」,u'name ',u'city',u'IATA',u'delay',u'state',u'weather']

+0

你不應該在'airport_data'而不是'airport_response'上調用'dict(..)'嗎?現在它會將整個響應字符串看作單個項目,並且由於字典需要鍵/值,因此會出錯。 –

回答

0

您的dict() shouldn' t與response一起使用,但與json一起使用,所以使用dict(airport_response)會導致錯誤,因此應該使用airport_data而不是airport_data = dict(airport_data)。下面是你想要的一個例子:

import json 
import requests 

url_parameters = { 
    "format": "json" 
} 

base_url = 'http://services.faa.gov/airport/status/' 
airport = 'DTW' 

airport_response = requests.get(base_url + airport, params=url_parameters) 
airport_data = airport_response.json() 
airport_data = dict(airport_data) 

airport_data_keys = [] 
for key, value in airport_data.items(): 
    airport_data_keys.append(key) 

print airport_data_keys 
+0

偉大的工作!最後一件事情是,如果我想要這些鍵然後在Unicode列表中打印,我將如何執行該操作?我嘗試打印airport_data_keys('utf8'),但它返回了錯誤TypeError:'Unicode'對象不可調用。 –

+0

@SammySmith你有一點幫助,我也更新了我的代碼。你需要的是將每個鍵都附加到列表中。 –