Python会在合并两个json文件时将附加的paratheses []附加到json文件中

问题描述 投票:0回答:1

[嗨,我目前正在尝试将多个具有相同结构的json文件合并到一个json文件中。

追加有效,但它会将括号[]与生成的json文件添加到新文件中。

代码获取主要的json filename.txt并添加filename _ 1。txt来查找它,它将打开它,打开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)
python json
1个回答
0
投票

我没有输入文件中的内容,但我认为您可以使用extend方法代替append方法来解决您的问题。

json_final_object[reportName].extend(list_to_read)
© www.soinside.com 2019 - 2024. All rights reserved.