我对python很陌生,我有一个需要转换为csv的大型json文件-下面是一个示例
{“地位”:“成功”、“名称”:“特里萨·梅”、“地点”:"87654321“、"AccountCategory":”业务“、"AccountType":”当前“、"TicketNo":"12345-12”、"AvailableBal":"12775.0400“、"BookBa":"123475.0400”、"TotalCredit":"1234567“、"TotalDebit":"0”、“用法”:"5",“期间”:“2014年5月11日至2014年7月11日”、“货币”、“申请人”:“天使”、“签字人”:{“姓名”:“不可得”、“BVB”:“无资料”}、“详细资料”:{“PTransactionDate”:“24-7l-14”、“PValueDate”:“24-7l-13”、“PNarration”:“CashDe存放”、"PCredit":"0.0000“、"PDebit":"40003.0000","PBalance":"40003.0000"},{“PTransactionDate”:“24-7l-14”,“PValueDate”:“23-7l-14”,“PTest”:“现金存款”,"PCredit":"0.0000","PDebit":"40003.0000","PBalance":"40003.0000"},{“PTransactionDate”:“25-7l-14”,“PValueDate”:“22-71-14”,“PTest”:“现金存款”,"PCredit":"0.0000","PDebit":"40003.0000","PBalance":"40003.0000"},{“PTransactionDate”:“25-71-14”,“PValueDate”:“21-7月-14日”,“PTest”:“现金存款”,"PCredit":"0.0000","PDebit":"40003.0000","PBalance":"40003.0000"},{“PTransactionDate”:“25-7月-14”,“PValueDate”:“20-7月-14”,“PTest”:“卡什·存款”,"PCredit":"0.0000","PDebit":"40003.0000",“PBalance”:“40003.0000”}
我需要这个作为
名称、地位、地点、帐户类别、帐户类型、可用情况、总贷方、总借方等列,
对于pcredit、pdebit、pbalance、ptransactiondate、pvaluedate和“ptest”,每一行都有新的值,如JSON文件所示
我已经设法把下面的脚本放在一起在线查看,但是它在最后给我展示了一个空的csv文件。我做错了什么?我已经使用了在线json到csv转换器,它可以工作,但是,由于这些是敏感的文件,我希望用我自己的脚本来编写/管理,这样我就能确切地看到它是如何工作的。关于我的python脚本,请看下面的内容--我能给出一些修改的建议吗?谢谢
import csv
import json
infile = open("BankStatementJSON1.json","r")
outfile = open("testing.csv","w")
writer = csv.writer(outfile)
for row in json.loads(infile.read()):
writer.writerow(row)
import csv, json, sys
# if you are not using utf-8 files, remove the next line
sys.setdefaultencoding("UTF-8") # set the encode to utf8
# check if you pass the input file and output file
if sys.argv[1] is not None and sys.argv[2] is not None:
fileInput = sys.argv[1]
fileOutput = sys.argv[2]
inputFile = open("BankStatementJSON1.json","r") # open json file
outputFile = open("testing2.csv","w") # load csv file
data = json.load("BankStatementJSON1.json") # load json content
inputFile.close() # close the input file
output = csv.writer("testing.csv") # create a csv.write
output.writerow(data[0].keys()) # header row
for row in data:
output.writerow(row.values()) # values row发布于 2018-03-20 20:06:20
这适用于您发布的JSON示例。问题是,您有嵌套的dict,不能根据需要为pcredit, pdebit, pbalance, ptransactiondate, pvaluedate and ptest创建子标题和子行。
您可以使用csv.DictWriter
import csv
import json
with open("BankStatementJSON1.json", "r") as inputFile: # open json file
data = json.loads(inputFile.read()) # load json content
with open("testing.csv", "w") as outputFile: # open csv file
output = csv.DictWriter(outputFile, data.keys()) # create a writer
output.writeheader()
output.writerow(data)发布于 2018-03-20 19:29:29
确保在结束时也关闭输出文件。
https://stackoverflow.com/questions/49391821
复制相似问题