首页 > 解决方案 > 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)

标签: pythonjson

解决方案


我不知道您的输入文件中有什么,但我认为您可以使用该extend方法而不是该append方法来解决您的问题。

json_final_object[reportName].extend(list_to_read)

推荐阅读