Json2csv

import json,csv,sys
a=sys.argv[1]
print(a)

def json_to_csv():
    with open(a, "r",encoding='UTF-8') as  f:
        data = f.read()
    jsonData = json.loads(data)

    csvfile = open("result.csv", "w", newline='')#保存结果
    keys_write = True
    writer = csv.writer(csvfile)
    # print(jsonData)
    for dic in jsonData:
        if keys_write:
            keys = list(dic.keys())
            # print(keys)
            writer.writerow(keys)
            keys_write = False
        writer.writerow(list(dic.values()))
        # print(list(dic.values()))
    csvfile.close()

if __name__ == "__main__":
    json_to_csv()
    print('转换完毕')

使用方法,将以上代码存为json2csv.py,
windows命令行下,切换到要转换的json文件目录,输入:

json2csv.py 待转换的json文件全名

结果将保存在待转换的json文件同目录result.csv文件里。

你可能感兴趣的:(Json2csv)