大家好,我对python很新,所以请耐心等待。 我有一个这种格式的示例json文件。
[{
"5":"5",
"0":"0",
"1":"1"},{
"14":"14",
"11":"11",
"15":"15"},{
"25":"25",
"23":"23",
"22":"22"}]
我想以特定的方式将json文件转换为csv。 1映射中的所有值,即json中的{
和}
都应该转换为csv文件(比如FILE_A.csv)。
对于上面的例子,
FILE_A.csv,
DAILY,COUNT
5,5
0,0
1,1
FILE_B.csv,
WEEKLY,COUNT
14,14
11,11
15,15
FILE_C.csv,
MONTHLY,COUNT
25,25
23,23
22,22
json中只有3张地图。
有人能建议将json中的3个地图转换为上述结构的3个不同csv文件的最佳方法吗?
提前致谢。
答案 0 :(得分:0)
您可以使用包含所需数据的简单循环,如下所示:
jsondata = [{
"5":"5",
"0":"0",
"1":"1"},{
"14":"14",
"11":"11",
"15":"15"},{
"25":"25",
"23":"23",
"22":"22"}]
for name, timelapse, data in zip(("A", "B", "C"),
("DAILY", "WEEKLY","MONTHLY",),
jsondata): #get data together
with open("path/to/your/FILE_{}".format(name), "w") as f:
f.write("{}, COUNT\n".format(timelapse)) # write header
f.write("\n".join(",".join((k,v)) for k,v in data.items())) #write data separated by ','
这里有live example
另请查看csv
模块
答案 1 :(得分:0)
data_list = [{
"5":"5",
"0":"0",
"1":"1"},{
"14":"14",
"11":"11",
"15":"15"},{
"25":"25",
"23":"23",
"22":"22"}]
temp_dct = { "DAILY": data_list[0], "WEEKLY": data_list[1], "MONTHLY": data_list[2]}
file_name_ord = 65
for k in ["DAILY", "WEEKLY", "MONTHLY"]:
v = temp_dct[k]
file_name = "FILE_"+str(chr(file_name_ord))+".csv"
file_name_ord+=1
data = k + ","+ "COUNT\n"
for inner_k, inner_v in v.items():
data += inner_k + ","+inner_v+"\n"
with open(file_name, "w") as f:
f.write(data)
也尝试这个。希望你能得到答案。
答案 2 :(得分:0)
直接解决方案:
import json, csv
with open('FILE_A.csv', 'w', newline='') as fa, open('FILE_B.csv', 'w', newline='') as fb, \
open('FILE_C.csv', 'w', newline='') as fc:
a_writer, b_writer, c_writer = csv.writer(fa), csv.writer(fb), csv.writer(fc)
da, db, dc = json.load(open('your.json'))
a_writer.writerow(('DAILY','COUNT'))
a_writer.writerows(da.items())
b_writer.writerow(('WEEKLY','COUNT'))
b_writer.writerows(db.items())
c_writer.writerow(('MONTHLY','COUNT'))
c_writer.writerows(dc.items())