如何在python中将json转换为csv [英] how to convert json to csv in python
本文介绍了如何在python中将json转换为csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的json文件输入
Following is my json file input
{"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次.如何解决此问题.
So, here I did got my answer but instead of printing it once, It is printing 7 times.. How do I fix this.
推荐答案
BankData
是您不需要对其进行迭代的dict.您可以使用键直接访问值.
BankData
is a dict you do not need to iterate it. You can directly access the values using the key.
例如:
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"]])
这篇关于如何在python中将json转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文