我在 python 中有一个具有以下 json 格式的文件:
{"header":{"a":"1","b":"1"},
"data":[{"a":"1", "b":{"ba":"b1","bb":"b2","bc":"b3"}, "c":{"ca":"x1","cb":"x2","cc":"x3"}, "d":"4"},
{"a":"12", "b":{"ba":"12a","bb":"12ab","bc":"1ab"},"c":{"ca":"12z","cb":"12zz","cc":"12zzz"}, "d":"12"}
]}
我编写了一个没有嵌套“b”和“c”元素的 csv 解析器,但是在尝试将“b”和“c”中的选定元素解析到我的 csv 时遇到了困难。这是我到目前为止所拥有的:
#load json
try:
with open('tmp.p', 'rb') as f:
myjson = json.load(f)
except IOError:
print("Error converting to json")
#write selected json to a csv output file
out = open(savedpath, 'a+')
try:
#add or remove data to parse here
mydata = ('d','b','a')
mycsv = csv.DictWriter(out, fieldnames=mydata, quoting=csv.QUOTE_ALL, extrasaction='ignore', lineterminator='\n')
mycsv.writeheader()
for row in myjson["data"]:
mycsv.writerow(row)
finally:
out.close()
我已将嵌套元素解析为单独的临时文件:
# parse nested elements ##
try:
#add or remove Port1/Port2 data to parse here
myport = ('bb','ba')
tmp3 = csv.DictWriter(t3, fieldnames=myport, quoting=csv.QUOTE_ALL, extrasaction='ignore', lineterminator='\n')
tmp3.writeheader()
tmp4 = csv.DictWriter(t4, fieldnames=myport, quoting=csv.QUOTE_ALL, extrasaction='ignore', lineterminator='\n')
tmp4.writeheader()
#print myjson["data"][0]["b"]["bb"]
#print myjson["data"][0]["c"]["bb"]
for row in myjson["data"]:
data1 = row["b"]
data2 = row["c"]
#print data1["bb"]
tmp3.writerow(data1)
tmp4.writerow(data2)
finally:
t3.close()
t4.close()
但是我在尝试加入数据时遇到了麻烦。我希望数据在我的 csv 中看起来像这样:
#header
a:1
b:1
#data
a,d,ba,bc,ca,cc
1,4,b1,b3,x1,x3
12,12,12a,1ab,12z,12zzz
我在尝试编写我的 csv 文件时被卡住了。我想我想多了,但是因为我认为使用连接字符串可能有效,但它没有:
try:
with open('tmp3.p', 'rb') as port1:
with open('tmp4.p', 'rb') as port2:
with open('tmp5.p', 'rb') as general:
for rport1 in port1:
for rport2 in port2:
for rgen in general:
rport1 = str.replace(rport1,"\n","")
rport2 = str.replace(rport2,"\n","")
rgen = str.replace(rgen,"\n","")
string = ("%s,%s,%s" % (rgen, rport1, rport2))
print string
我使用 DictWriter 因为我需要按特定顺序解析文件。我知道我在尝试组合数据时违背了使用 json 的目的,这是一个非常糟糕的做法,但我不确定如何继续。预先感谢您的帮助...