如何使用python把json文件转换为csv文件

@

了解json整体格式

这里有一段json格式的文件,存着全球陆地和海洋的每年异常气温(这里只选了一部分):global_temperature.json

{
  "description": {
    "title": "Global Land and Ocean Temperature Anomalies, January-December",
    "units": "Degrees Celsius",
    "base_period": "1901-2000"
  },
  "data": {
    "1880": "-0.1247",
    "1881": "-0.0707",
    "1882": "-0.0710",
    "1883": "-0.1481",
    "1884": "-0.2099",
    "1885": "-0.2220",
    "1886": "-0.2101",
    "1887": "-0.2559"
  }
}

通过python读取后可以看到其实json就是dict类型的数据,description和data字段就是key
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210312161305572.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0RURlRf,size_16,color_FFFFFF,t_70)
由于json存在层层嵌套的关系,示例里面的data其实也是dict类型,那么年份就是key,温度就是value
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210312161557365.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0RURlRf,size_16,color_FFFFFF,t_70)

转换格式

现在要做的是把json里的年份和温度数据保存到csv文件里

提取key和value

这里我把它们转换分别转换成int和float类型,如果不做处理默认是str类型

year_str_lst = json_data['data'].keys()
year_int_lst = [int(year_str) for year_str in year_str_lst]

temperature_str_lst = json_data['data'].values()
temperature_int_lst = [float(temperature_str) for temperature_str in temperature_str_lst]

print(year_int)
print(temperature_int_lst)

![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210312163242118.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0RURlRf,size_16,color_FFFFFF,t_70)

使用pandas写入csv

import pandas as pd

# 构建 dataframe
year_series = pd.Series(year_int_lst,name='year')
temperature_series = pd.Series(temperature_int_lst,name='temperature')

result_dataframe = pd.concat([year_series,temperature_series],axis=1)

result_dataframe.to_csv('./files/global_temperature.csv', index = None)

axis=1,是横向拼接,若axis=0则是竖向拼接
最终效果
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210312164100236.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0RURlRf,size_16,color_FFFFFF,t_70)

注意
如果在调用to_csv()方法时不加上index = None,则会默认在csv文件里加上一列索引,这是我们不希望看见的
![在这里插入图片描述]( https://img-blog.csdnimg.cn/20210312163923615.png?x-oss-process=image/watermark ,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0RURlRf,size_16,color_FFFFFF,t_70)

posted @ 2021-03-12 16:44  孙晨c  阅读(3098)  评论(0)    收藏  举报