簡體   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