繁体   English   中英

如何将 JSON 文件转换为 CSV

[英]How to convert JSON file to CSV

我有以下 JSON 文件:

[
    {
      "Names": {
         "0": "Nat",
         "1": "Harry",
         "2": "Joe"
      },
      "Marks": {
         "0": 78.22,
         "1": 32.54,
         "2": 87.23
      }
   }
]

我编写了以下代码进行转换:

import csv, json

def conversion(Jsonfile,Csvfile):
    readfile=open(Jsonfile,"r")
    print(readfile)
    jsondata=json.load(readfile)
    print(jsondata)
    readfile.close()
    
    data_file=open(Csvfile,'w')
    csv_writer=csv.writer(data_file)
    
    count=0
    for data in jsondata:
        if count==0:
            header=data.keys()
            print(header)
            csv_writer.writerow(header)
            count=count+1
        
        csv_writer.writerow(data.values())
        print(data.values())
    data_file.close()

Jsonfile="Series.json"
Csvfile="convertedfile.csv"

conversion(Jsonfile,Csvfile)

我在 CSV 中得到以下输出

Names,Marks

"{'0': 'Nat', '1': 'Harry', '2': 'Joe'}","{'0': 78.22, '1': 32.54, '2': 87.23}"

我的问题是如何更正代码以获得以下输出(即每个名称在不同的行中带有标记):

Names,Marks
0,Nat,78.22
1,Harry,32.54
2,Joe,87.23

pandas具有两者的实用程序,读取 json 和写入 csv。

import pandas as pd


 j = '[{"Names":{"0":"Nat","1":"Harry","2":"Joe"},"Marks":{"0":78.22,"1":32.54,"2":87.23}}]'
df = pd.read_json(j[1:-1], orient='records')  # 1:-1 because we need to remove the square brackets
df.to_csv("output.csv")

输出:

,Names,Marks
0,Nat,78.22
1,Harry,32.54
2,Joe,87.23

这是一种方法。

首先,我们打开 json 文件并解析它:

import json

json_file = "foo.json"
csv_file = "foo.csv"

with open(json_file, "r") as f:
    json_data = json.load(f)

然后我们从 json 列表中提取字典:

my_dict = json_data[0]  # we get the dict inside the list
my_list = []  # we create a new list to store data in the format we need

我们以一种可以轻松将其打印到文件的方式格式化数据:

for key in my_dict["Names"].keys():
    my_list.append(
        [
            key,
            my_dict["Names"][key],
            str(my_dict["Marks"][key])  # we cast the mark to string so it's easier to use later on
        ]
    )

现在,数据以一种易于打印的方式格式化,因此我们只需将其保存在 csv 文件中!

# Our new list is now created, we can now save it to our file
with open(csv_file, "w") as f:
    f.write("Names,Marks\n")
    for line in my_list:
        f.write(",".join(line) + "\n")

输出:

Names,Marks
0,Nat,78.22
1,Harry,32.54
2,Joe,87.23
import pandas as pd

df = pd.read_json(r'Path where the JSON file is saved\File Name.json')
df.to_csv(r'Path where the new CSV file will be stored\New File Name.csv', index = None)

您可以从 JSON 数据生成有效的 CSV 文件,而无需使用pandascsv等重量级模块。 您只需要json模块从文件加载 JSON 数据并(隐式)验证它。

import json

Jsonfile = 'Series.json'
Csvfile = 'convertedfile.csv'

with open(Jsonfile) as jfile:
    d = json.load(jfile)[0]

    with open(Csvfile, 'w') as cfile:
        print('ID,Name,Marks', file=cfile)
        if names := d.get('Names'):
            for id_, name in names.items():
                mark = d.get('Marks', {}).get(id_, '')
                print(f'{id_},{name},{mark}', file=cfile)

输出文件将如下所示:

ID,Name,Marks
0,Nat,78.22
1,Harry,32.54
2,Joe,87.23

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM