使用Python从JSON API中提取多个数据

时间:2015-08-13 14:35:54

标签: python json dictionary

我可以从网址中提取特定数据。

    weather_data = r.get("http://api.openweathermap.org/data/2.5/weather?q=" + location)
    json_weather = weather_data.text
    weather_info = json.loads(json_weather)

    print weather_info['coord']['lat']
    print weather_info['coord']['lon']

以下是API上的Diplayed

问题是,如何提取多个数据并放入1个列表(dict)而不是逐个提取。

例如,我想把' lat',' lon','湿度'在同一个清单中。

{u'base': u'stations',
 u'clouds': {u'all': 40},
 u'cod': 200,
 u'coord': {u'lat': 51.51, u'lon': -0.13},
 u'dt': 1439476222,
 u'id': 2643743,
 u'main': {u'humidity': 88,
           u'pressure': 1012,
           u'temp': 291.71,
           u'temp_max': 293.15,
           u'temp_min': 290.15},
 u'name': u'London',
 u'rain': {u'1h': 1.78},
 u'sys': {u'country': u'GB',
          u'id': 5091,
          u'message': 0.0242,
          u'sunrise': 1439440988,
          u'sunset': 1439493986,
          u'type': 1},
 u'visibility': 9000,
 u'weather': [{u'description': u'light intensity shower rain',
               u'icon': u'09d',
               u'id': 520,
               u'main': u'Rain'}],
 u'wind': {u'deg': 60, u'speed': 4.6}}

1 个答案:

答案 0 :(得分:1)

我认为您要问的是,如何仅从该数据集中提取纬度,经度和湿度值。

如果是这种情况,请尝试此版本。它采用列表locations中的每个位置,然后收集坐标和湿度指数:

import requests

url = 'http://...' # url goes here
locations = ['London', 'New York', 'Chicago'] # adjust as required
results = {}

for loc in locations:
   response = requests.get(url, params={'q': loc})
   if response.status_code == 200:
       data = response.json()
       results[loc] = {'lat': data[u'coord'][u'lat'],
                       'lon': data[u'coord'][u'lon'],
                       'humidity': data[u'main'][u'humidity']}
   else:
       print('No results for {}'.format(loc))

print(results)

确保您拥有最新版本的请求(pip install -U requests)。

相关问题