python解析json文件信息到csv中
json格式多种多样,本代码着重看函数部分
import json, csv, os import pandas as pd josns_root = 'jsons' csvs_root = 'csvs' list_josn = os.listdir(josns_root) for bb in list_josn: path_json_ = bb #请修改json路径 path_json = os.path.join(josns_root, path_json_) path_csv_ = path_json_.split('.')[0]+'.csv' path_csv = os.path.join(csvs_root, path_csv_) if os.path.exists(path_csv): print('路径已存在,请解决冲突', path_csv) exit() open(path_csv, 'w').close() list_ = [200,50,51] f = open(path_json, encoding='utf-8') # 载入json文件 setting = json.load(f) data = setting['data'] data1 = data['imgs'] print(type(data1)) headers = ['fov_id', 'cells_fit', 'cells_P', 'cells_N'] with open(path_csv, 'a')as csvfile: writer = csv.writer(csvfile) writer.writerow(headers) # 写每列标题 csvfile.close() cnt = 1 for i in data1: print('当前FOV编号:',cnt) cnt = cnt + 1 i_dict = dict(i) FOV_id = i_dict['id'] cells = i_dict['cells'] type_la = [] total_la = [] for m in cells: m_dict = dict(m) type_ = m_dict['type'] total = m_dict['total'] #print(type_, total) type_la.append(type_) total_la.append(total) out_ = dict(zip(type_la,total_la)) str1 = [None,None,None] cnt_ = 0 cnt__ = 0 for lala in list_: if len(list(out_.keys())) == 0: continue if lala in list(out_.keys()): str1[cnt_] = list(out_.values())[cnt__] cnt__ = cnt__ + 1 cnt_ = cnt_ + 1 rows = [str(FOV_id), str1[0], str1[2], str1[1]] with open(path_csv, 'a')as csvfile: writers = csv.writer(csvfile, delimiter=',') writers.writerow(rows) # 按行写入csv csvfile.close() print('==============task OK!================')