简体   繁体   English

将地图数组json转换为csv

[英]Convert map array json to csv

Hello all I'm very new to python, so just bear with me. 大家好,我是python的新手,所以请多多包涵。 I have a sample json file in this format. 我有这种格式的示例json文件。

[{
"5":"5",
"0":"0",
"1":"1"},{
"14":"14",
"11":"11",
"15":"15"},{
"25":"25",
"23":"23",
"22":"22"}]

I would like to convert the json file to csv in a specific way. 我想以特定方式将json文件转换为csv。 All the values in 1 map ie, { and } in the json should be converted to a csv file(say FILE_A.csv). 1个映射中的所有值,即json中的{}应该转换为一个csv文件(例如FILE_A.csv)。

For the above example, 对于以上示例,

FILE_A.csv, FILE_A.csv,

DAILY,COUNT
5,5
0,0
1,1

FILE_B.csv, FILE_B.csv,

WEEKLY,COUNT
14,14
11,11
15,15

FILE_C.csv, FILE_C.csv,

MONTHLY,COUNT
25,25
23,23
22,22

There will only be 3 maps in the json. json中只会有3张地图。

Can anyone suggest the best way to convert the 3 maps in the json to 3 different csv files of the above structure? 谁能建议将json中的3个映射转换为上述结构的3个不同的csv文件的最佳方法?

Thanks in advance. 提前致谢。

You can use a simple loop with all the data you need, should look like this: 您可以对所有需要的数据使用简单的循环,如下所示:

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 ','

Here you have a live example 这里有一个现场例子

Also take a look at the csv module 还看看csv模块

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)

Try this one also. 也尝试这个。 Hope you will get your answer. 希望你能得到答案。

Straight-forward solution: 简单的解决方案:

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM