将JSON转换为CSV文件

时间:2019-12-20 10:10:33

标签: python json pandas csv

我去过这里几次,但似乎无法解决。我正在尝试将JSON转换为CSV文件。我继续收到此错误: 从None引发JSONDecodeError(“期望值”,s,err.value)JSONDecodeError:期望值。 请帮忙。 这是我要使用的代码。

import json 
import pandas as pd 

# load json object
with open('C:/Users/gavin/OneDrive/Desktop/4th Year/DAD project/mass.json', 'r') as f:
   d = json.load(f)

multi = []; inner = {}

def recursive_extract(i):
    global multi, inner

    if type(i) is list:
        if len(i) == 1:
            for k,v in i[0].items():
                if type(v) in [list, dict]:
                    recursive_extract(v)
                else:                
                    inner[k] = v
        else:
            multi = i

    if type(i) is dict:
        for k,v in i.items():
            if type(v) in [list, dict]:
                recursive_extract(v)
            else:                
                inner[k] = v

recursive_extract(d['data'])

data_dict = []
for i in multi:    
    tmp = inner.copy()
    tmp.update(i)
    data_dict.append(tmp)

df = pd.DataFrame(data_dict)
df.to_csv('Output.csv')

更新:这是我要转换为CSV文件的JSON。我必须删除一些记录,以便堆栈溢出可以让我发布问题。

{
  "data": [
    {
      "value": 4070,
      "data_year": 1998,
      "month_num": 0,
      "key": "Unknown"
    },
    {
      "value": 1095,
      "data_year": 1992,
      "month_num": 0,
      "key": "Unknown"
    },
    {
      "value": 11277,
      "data_year": 2017,
      "month_num": 0,
      "key": "Unknown"
    },
      {
      "value": 3481,
      "data_year": 1993,
      "month_num": 0,
      "key": "Unknown"
    },
    {
      "value": 9402,
      "data_year": 2013,
      "month_num": 0,
      "key": "Unknown"
    },
    {
      "value": 473,
      "data_year": 1991,
      "month_num": 0,
      "key": "Unknown"
    },
    {
      "value": 9587,
      "data_year": 1998,
      "month_num": 0,
      "key": "None"
    },
    {
      "value": 244,
      "data_year": 1992,
      "month_num": 0,
      "key": "None"
    }
],
"precise_data": []
}

1 个答案:

答案 0 :(得分:0)

您也许可以使用pandas内置功能将json文件读取到pandas数据框

df=pd.read_json("temp.json")

读取文件后,可以通过以下方式将其另存为csv文件:

df.to_csv('temp.csv' , index = False) 

如果这不起作用,

您可以尝试以下任一方法,根据其结构读取

data= pd.read_json('Data.json', lines=True)
data= pd.read_json('Data.json', lines=True, orient='records') 
data= pd.read_json('Data.json', orient=str)