1. 程式人生 > >如何使用python把json檔案轉換為csv檔案

如何使用python把json檔案轉換為csv檔案

@[toc] # 瞭解json整體格式 這裡有一段json格式的檔案,存著全球陸地和海洋的每年異常氣溫(這裡只選了一部分):global_temperature.json ```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`型別 ```python 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 ```python 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_FFFFF