我是python新手,我有一个需要转换成csv的大json文件-下面是一个示例
{“status”:“success”,“Name”:“Theresa May”,“Location”:“87654321”,“AccountCategory”:“Business”,“AccountType”:“Current”,“TicketNo”:“12345-12”,“AvailableBal”:“12775.0400”,“BookBa”:“123475.0400”,“TotalCredit”:“1234567”,“TotalDebit”:“0”,“用法”:“5”,“Period”:“2014年5月11日至2014年7月11日”,“货币”:“GBP”,“申请人”:“天使”,“签署人”:[{“Name”:“不可用”,“BVB”:“不可用”}],“详细信息”:[{“PTransactionDate”:“24-Jul-14”,“PValueDate”:“24-Jul-13”,“pnarrantion”:“现金存款”,“PCredit”:“0.0000”,“PDebit”:“40003.0000”,“PBalance”:“40003.0000”},{“PTransactionDate”:“24-Jul-14”,“PValueDate”:“2014年7月23日”,“PTest”:“现金存款”,“PCredit”:“0.0000”,“PDebit”:“40003.0000”,“PBalance”:“40003.0000”},{“PTransactionDate”:“25-Jul-14”,“PValueDate日期”:“22-7-14”,“22-7-14”,“PTest”:“现金存款”,“PCredit”:“0.0000”,“PDebit”:“40003.0000万”,“PBalance”:“40003.0000“的,{“PTTransactionDate““25-Jul-14,“PValue日期:““21-7月14日,“21-7月14日,“PTest“:“现金存款,“PCCredit:“0.0000,“PDEB息他们:“40003.0000,“PBalance“““40003.0000,“PBalance“““40003.0000““““40003.0000““““40003.0000“““““““““““““2014年7月25日”,“PValueDate”:“2014年7月20日”,“PTest”:“现金存款”,“PCredit”:“0.0000”,“PDebit”:“40003.0000”,“PBalance”:“40003.0000”}]}
我需要这个来证明
名称、状态、位置、accountcategory、accounttype、availablebal、totalcredit、totaldebit等列
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
这适用于您发布的JSON示例。问题是您已经嵌套了
dict
,并且您无法根据需要为pcredit, pdebit, pbalance, ptransactiondate, pvaluedate and ptest
创建子标题和子行。在您可以使用
csv.DictWriter
:确保最后也要关闭输出文件。在
相关问题 更多 >
编程相关推荐