python - Python在合并两个json文件时将额外的paratheses []添加到json文件中
问题描述
您好我目前正在尝试将多个具有相同结构的 json 文件合并到一个 json 文件中。
追加有效,但它将括号 [] 添加到带有结果 json 文件的新文件中。
代码是获取主要的 json filename.txt 并添加 filename _1 .txt 来找到它,它将打开它, open filename _2 .txt 获取一个列表并将其添加到 filename _1 .txt
结果 Json 文件:
{
"DateTimeUTC": "/Date(1590149927318)/",
"Journals": [
{
"JournalNumber": 1,
"JournalLines": [
{
"JournalLineID": "a",
"AccountID": "1a"
}
]
},
[
{
"JournalDate": "/Date(1415836800000+0000)/",
"JournalNumber": 2,
"JournalLines": [
{
"JournalLineID": "a",
"AccountID": "2a"
}
]
}
]
]
}
这是我用来合并 json 文件的代码。
import json
def ConcatJsonFiles(report_path, reportName, file_number):
file_number = file_number + 1
print("\n Concatinating Reports....")
for l in range(2, file_number):
result_file = report_path[:-4]
result_file = result_file + "_1.txt"
print ("\n" + result_file + "\n")
with open(result_file, 'r') as json_result_file:
json_final_object = json.load(json_result_file)
final_list = json_final_object[reportName]
print(final_list)
read_file = report_path[:-4]
read_file = read_file + "_" + str(l) + ".txt"
with open(read_file, 'r') as temp_json_file:
temp_json_object = json.load(temp_json_file)
list_to_read = temp_json_object[reportName]
json_final_object[reportName].append(list_to_read)
# final_list.append(list_to_read)
with open(result_file, 'w') as json_result:
json.dump(json_final_object, json_result, indent=4)
print("\n Report " + reportName + " ready! > " + report_path + "\n")
# **********************************************
report_path = "/Users/kris/xero.txt"
reportName = "Journals"
total_files = 2
ConcatJsonFiles(report_path, reportName, total_files)
解决方案
我不知道您的输入文件中有什么,但我认为您可以使用该extend
方法而不是该append
方法来解决您的问题。
json_final_object[reportName].extend(list_to_read)
推荐阅读
- github - 如何查看我投票的 github 问题列表
- node.js - NextJS+Express: body 被注入了一个 display:none CSS 属性
- java - AAPT:错误:未找到属性 buttonColor(又名 com.example.*appName*)
- matlab - 将复杂向量从 Matlab 保存到文本文件
- angular8 - Amcharts:如何更改地图的颜色?
- mysql - 使用 str_to_date 函数从文件中将数据加载到 MySQL 中的日期时间值不正确
- openiddict - 如何使用 OpenIddict 通过电话和短信(无密码)对用户进行身份验证
- c# - 在c#中检测文本框中的换行符
- ios - 在 MultipeerConnectivity 中扫描时看不到附近的设备
- javascript - 如何将对象数组和嵌套数组分解为具有单个数据的分隔数组