使用Python从JSON API提取多个数据
我能够从url中提取特定数据使用Python从JSON API提取多个数据,python,json,dictionary,Python,Json,Dictionary,我能够从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['c
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上显示的内容
问题是,我如何提取多个数据并放入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}}
我想你要问的是,如何从数据集中只提取纬度、经度和湿度值 如果是这种情况,请尝试此版本。它获取列表中的每个位置
位置
,然后收集坐标和湿度指数:
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
)。不清楚您在问什么。在本例中,weather\u info
是一个Python字典。weather\u info是一个字典(或列表,但不太可能)。JSON对象由转换为字典。@larsks,我现在已经更详细地澄清了我的问题