【发布时间】:2018-08-29 17:11:35
【问题描述】:
我是 python 新手,我有一个大型 json 文件需要转换为 csv - 下面是一个示例
{ "status": "success","Name": "Theresa May","Location": "87654321","AccountCategory": "Business","AccountType": "Current","TicketNo": " 12345-12","AvailableBal":"12775.0400","BookBa":"123475.0400","TotalCredit":"1234567","TotalDebit":"0","Usage":"5","Period":" 2014 年 5 月 11 日至 2014 年 7 月 11 日”,“货币”:“英镑”,“申请人”:“天使”,“签字人”:[{“姓名”:“不可用”,“BVB”:“不可用”}] ,"Details": [{"PTransactionDate":"24-Jul-14","PValueDate":"24-Jul-13","Pnarration":"Cash Deposit","PCredit":"0.0000","PDebit ":"40003.0000","PBalance":"40003.0000"},{"PTransactionDate":"24-Jul-14","PValueDate":"23-Jul-14","PTest":"现金存款"," PCredit":"0.0000","PDebit":"40003.0000","PBalance":"40003.0000"},{"PTransactionDate":"25-Jul-14","PValueDate":"22-Jul-14"," PTest":"Cash Deposit","PCredit":"0.0000","PDebit":"40003.0000","PBalance":"40003.0000"},{"PTransactionDate":"25-Jul-14","PValueDate": "21-Jul-14","PTest":"现金存款","PCredit":"0.0000","PDebit":"40003.0000","PBalance":"40003.0000" },{"PTransactionDate":"25-Jul-14","PValueDate":"20-Jul-14","PTest":"Cash Deposit","PCredit":"0.0000","PDebit":"40003.0000 ","PBalance":"40003.0000"}]}
我需要这个显示为
name、status、location、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 文件没有行,它有键和值。