【问题标题】:Extract multiple data from JSON API using Python使用 Python 从 JSON API 中提取多个数据
【发布时间】:2015-08-13 14:35:53
【问题描述】:

我能够从 url 中提取特定数据。

    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 上显示的内容

问题是,我怎样才能提取多个数据并将其放入一个列表(dict)中,而不是一个一个地提取它。

例如,我想将“纬度”、“经度”、“湿度”放在同一个列表中。

{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}}

【问题讨论】:

  • 不清楚你在问什么。在这个例子中,weather_info一个 Python 字典。
  • weather_info 是字典(或列表,但不太可能)。
  • JSON 对象 default 转换为字典。
  • @larsks,我现在已经更详细地澄清了我的问题

标签: python json dictionary


【解决方案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)。

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2017-04-16
    • 2014-03-07
    • 1970-01-01
    • 2020-05-06
    • 2021-09-25
    • 2017-02-12
    • 2020-06-02
    • 2021-03-27
    相关资源
    最近更新 更多