使用Python 3.7将多个JSON文件连接/合并到一个文件中

jvidinwx  于 2023-03-24  发布在  Python
关注(0)|答案(3)|浏览(218)

我在一个文件夹(~200)中有多个JSON文件,我想将其合并并生成一个JSON文件。

result = ''
for f in glob.glob("*.json"):
    with open(f, "r", encoding='utf-8') as infile:
        result += infile.read()
        
with open("merged_file.json", "w", encoding='utf-8') as outfile:
    outfile.writelines(result)

然而,它生成的文件与JSON内容,但所有的内容是在只有一行。我怎么能追加的内容,因为它是在文件中。

xv8emn3q

xv8emn3q1#

您可以通过阅读和解析每个JSON文件,将解析后的内容追加到列表中,
示例如下:

json_objects = []

for f in glob.glob("*.json"):
    try:
        with open(f, "r", encoding='utf-8') as infile:
            file_content = json.load(infile)
            json_objects.append(file_content)
    except json.JSONDecodeError as e:
        print(f"Error {f}: {e}")

with open("merged_file.json", "w", encoding='utf-8') as outfile:
    json.dump(json_objects, outfile, ensure_ascii=False, indent=4)
nwlqm0z1

nwlqm0z12#

也许是这样:

import json
import glob

all_config = {}

for f in glob.glob("*.json"):
    with open(f, "r", encoding='utf-8') as infile:
        json_content = json.load(infile)
        all_config.update(json_content)
        
        
with open("All.json", "w+") as outfile:
    outfile.write(str(json.dumps(all_config, indent=4)))
bnlyeluc

bnlyeluc3#

hi运行它,完成后您可以编辑ALL_DATA._json -〉ALL_DATA.json

import json
import glob

all_data = {}

for f in glob.glob("*.json"):
with open(f, "r", encoding='utf-8') as infile:
    json_content = json.loads(infile.read())
    all_data.update(json_content)
    
    
with open("All_DATA._json", "w+") as outfile:
    outfile.write(str(json.dumps(all_data, indent=4)))

相关问题