python将json对象映射为集合,因此对json文件的追加写入,就直接变为对集合的更新操作。
import json
#导入json包
data={}
#创建一个data集合用于接收并暂存数据
json_list=["cls_FinancialClassification_answer.json",\
"cls_MedicalClassification_answer.json",\
"intent_InsuranceIntentChange_answer.json",\
"intent_InsuranceIntentConsult_answer.json",\
"intent_InsuranceIntentSearch_answer.json",\
"nli_FinancialNLI_answer.json",\
"nli_MedicalNLI_answer.json",\
"senti_FinancialSentiment_answer.json",\
"sts_FinancialSimilarity_answer.json",\
"sts_MedicalSimilarity_answer.json"
]
#需要追加的json文件列表
此处需要提前创建并声明data的数据类型为集合,以保证之后更新操作的正确性。
遍历需要追加写入的json_list,并逐个更新到data集合中。
此处需要强调,如果json文件中有中文,需要 encoding='utf-8'
for json_file in json_list:
with open(json_file,encoding='utf-8') as f:
data.update(json.load(f))
使用json.dump方法将data集合输出为json文件。
#输出answer.json文件
with open('answer.json','w',encoding='utf-8') as w_f:
json.dump(data,w_f,ensure_ascii=False,indent=2)
完整代码:
import json
data={}
json_list=["cls_FinancialClassification_answer.json",\
"cls_MedicalClassification_answer.json",\
"intent_InsuranceIntentChange_answer.json",\
"intent_InsuranceIntentConsult_answer.json",\
"intent_InsuranceIntentSearch_answer.json",\
"nli_FinancialNLI_answer.json",\
"nli_MedicalNLI_answer.json",\
"senti_FinancialSentiment_answer.json",\
"sts_FinancialSimilarity_answer.json",\
"sts_MedicalSimilarity_answer.json"
]
for json_file in json_list:
with open(json_file,encoding='utf-8') as f:
data.update(json.load(f))
#输出answer.json文件
with open('answer.json','w',encoding='utf-8') as w_f:
json.dump(data,w_f,ensure_ascii=False,indent=2)