簡體   English   中英

如何在python中將json轉換為csv

[英]how to convert json to csv in python

以下是我的json文件輸入

{"userID": "679d3bad-155e-4b39-9ff7-7d564f408942", "Is salary credited before 5th": "Yes", "Avg Salary of last 3 months": 15453.33, "Avg Salary of last 6 months": 15290.5, "Avg Balance before salary of last 3 months": 113.15, "Avg Balance before salary of last 6 months": 105.22}

代碼

    with open('/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.json', "r") as f:
        BankData = json.loads(f.read())
    x = json.loads(json.dumps(BankData))
    f = csv.writer(open("/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.csv", "w"))
    f.writerow(["userID", "Is salary credited before 5th", "Avg Salary of last 3 months", "Avg Salary of last 6 months", "Avg Balance before salary of last 3 months", "Avg Balance before salary of last 6 months"])

    for y in x:
        f.writerow([x["userID"], x["Is salary credited before 5th"],
                    x["Avg Salary of last 3 months"],
                    x["Avg Salary of last 6 months"],
                    x["Avg Balance before salary of last 3 months"],
                    x["Avg Balance before salary of last 6 months"]])

輸出

userID,Is salary credited before 5th,Avg Salary of last 3 months,Avg Salary of last 6 months,Avg Balance before salary of last 3 months,Avg Balance before salary of last 6 months
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22
679d3bad-155e-4b39-9ff7-7d564f408942,Yes,15453.33,15290.5,113.15,105.22

所以,在這里我確實得到了答案,但它沒有打印一次,而是打印了 7 次。我該如何解決這個問題。

您還可以使用熊貓來處理數據幀,

dct = {"userID": "679d3bad-155e-4b39-9ff7-7d564f408942", "Is salary credited before 5th": "Yes", "Avg Salary of last 3 months": 15453.33,
       "Avg Salary of last 6 months": 15290.5, "Avg Balance before salary of last 3 months": 113.15, "Avg Balance before salary of last 6 months": 105.22}

import pandas as pd

df = pd.DataFrame.from_records(dct, index=[0])

df.to_csv('outputfile.csv')

BankData是一個你不需要迭代它的字典。 您可以使用密鑰直接訪問這些值。

前任:

import csv
import json

with open('/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.json') as infile:
    BankData = json.loads(infile.read())

with open("/Users/vrindabv/Documents/PycharmProjects/BankStatementEngine/test.csv", "w") as outfile:
    f = csv.writer(outfile)
    f.writerow(["userID", "Is salary credited before 5th", "Avg Salary of last 3 months", "Avg Salary of last 6 months", "Avg Balance before salary of last 3 months", "Avg Balance before salary of last 6 months"])
    f.writerow([BankData["userID"], BankData["Is salary credited before 5th"],
                BankData["Avg Salary of last 3 months"],
                BankData["Avg Salary of last 6 months"],
                BankData["Avg Balance before salary of last 3 months"],
                BankData["Avg Balance before salary of last 6 months"]])

您可以這樣做:讀取您的 JSON 並通過導入jsoncsv模塊寫入 CSV 文件

import json, csv
from collections import OrderedDict #To maintain key value pair order
_json=json.loads(open('data.json', 'r').read(), object_pairs_hook=OrderedDict) 
out=open('converted.csv', 'w')
writer = csv.writer(out)               #create a csv.write
writer.writerow(_json[0].keys())      # header row
for row in _json:
    writer.writerow(row.values())

GeekSambhu 的解決方案對我有用,只需稍作修改。 我修改了一點,因為像Vinsent,我看到了一個KeyError異常 如果 JSON 結構具有保存數據行數組的頂級對象(這被認為是 JSON 最佳實踐),人們可能會收到 KeyError。 假設有一個名為“數據”的頂級對象,您只需更改 GeekSambhu 解決方案的兩行代碼。

writer.writerow(_json['data'][0].keys()) # 標題行
對於 _json['data'] 中的行:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM