python - 在 Python 中对 JSON 文件进行排序并输出为 Excel
问题描述
我想获得我所在城市的天气预报。我从 Openweathermap 获得了一个 API,它给了我一个 json 文件。现在我想对这个 json 进行排序并将其输出为 excel。
到目前为止,我得到了这段代码(我编辑了 API):
import urllib.request
import json
import pandas
urllib.request.urlretrieve ("http://api.openweathermap.org/data/2.5/forecast?id=2867714&APPID=XXXXXXXXX","WeatherData.json")
with open('WeatherData.json') as f:
data = (line.strip() for line in f)
data_json = "[{0}]".format(','.join(data))
data=json.loads(data_json)
这会生成以下 JSON:
{
"city": {
"coord": {
"lat": 48.1374,
"lon": 11.5755
},
"country": "DE",
"id": 2867714,
"name": "Muenchen",
"sunrise": 1574231244,
"sunset": 1574263882,
"timezone": 3600
},
"cnt": 40,
"cod": "200",
"list": [
{
"clouds": {
"all": 86
},
"dt": 1574251200,
"dt_txt": "2019-11-20 12:00:00",
"main": {
"grnd_level": 941,
"humidity": 71,
"pressure": 1014,
"sea_level": 1014,
"temp": 278.95,
"temp_kf": -0.36,
"temp_max": 279.31,
"temp_min": 278.95
},
"sys": {
"pod": "d"
},
"weather": [
{
"description": "overcast clouds",
"icon": "04d",
"id": 804,
"main": "Clouds"
}
],
"wind": {
"deg": 63,
"speed": 2.86
}
},
{
"clouds": {
"all": 96
},
"dt": 1574262000,
"dt_txt": "2019-11-20 15:00:00",
"main": {
"grnd_level": 940,
"humidity": 85,
"pressure": 1013,
"sea_level": 1013,
"temp": 276.96,
"temp_kf": -0.27,
"temp_max": 277.23,
"temp_min": 276.96
},
"sys": {
"pod": "d"
},
"weather": [
{
"description": "overcast clouds",
"icon": "04d",
"id": 804,
"main": "Clouds"
}
],
"wind": {
"deg": 61,
"speed": 1.98
}
},
我刚刚使用了 2 个列表条目的示例来进行天气预报。json 包含 40 个(每天 8 个,共 5 天)。
我只需要温度、相对湿度和压力。其余的对我的应用程序没用。
解决方案
import urllib.request
import json
import pandas as pd
from pandas.io.json import json_normalize
data = urllib.request.urlopen("https://samples.openweathermap.org/data/2.5/forecast?id=2867714&appid=b1b15e88fa797225412429c1c50c122a1")
data = json.loads(data.read())
df=json_normalize(data['list'])
df['city']=data['city']['name']
#with all data
df.to_excel("sample.xls")
#with selected data
df = df[['main.temp','main.pressure','main.humidity','city']]
df.to_excel("moscow_temp.xls")
推荐阅读
- ansible - 尝试根据操作系统拆分我的 Ansible 剧本
- clickhouse - 如何知道数据何时插入到 clickhouse
- python - 添加 datetime.time 对象列表
- javascript - 正则表达式至少包含以下 3 个 [0-9]、[az]、[AZ] 或特殊字符($ 除外)
- vue.js -
如何使用列表字符串进行多项选择 - java - 有没有办法在不使用管道的情况下检查 Apache Beam sdk 中是否存在文件
- go - 界面[golang]中的字段?
- iot - 将 Grafana 连接到 Kapua 的 Elasticsearch
- machine-learning - 如何修复 Keras 中的“RecursionError:超出最大递归深度”
- actions-on-google - 多个谷歌用户使用同一帐户时的谷歌智能家居操作