You should use extend instead of append. It will add the items of the passed list to result instead of a new list:

files=['my.json','files.json',...,'name.json']

def merge_JsonFiles(filename):
    result = list()
    for f1 in filename:
        with open(f1, 'r') as infile:
            result.extend(json.load(infile))

    with open('counseling3.json', 'w') as output_file:
        json.dump(result, output_file)

merge_JsonFiles(files)
Answer from Akaisteph7 on Stack Overflow
🌐
PyPI
pypi.org › project › jsonmerge
jsonmerge · PyPI
Any properties that are present both in base and head are merged based on the strategy specified further down in the hierarchy (e.g. in properties, patternProperties or additionalProperties schema keywords). The objClass option allows one to request a different dictionary class to be used to hold the JSON object. The possible values are names that correspond to specific Python ...
      » pip install jsonmerge
    
Published   Jul 19, 2023
Version   1.9.2
Discussions

python 3.x - Merge multiple JSON files (more than two) - Stack Overflow
I would like to merge multiple JSON files into one file. All of those files have the same structure. For example I've created three files which would look like this: ExampleFile_1 { "i... More on stackoverflow.com
🌐 stackoverflow.com
Merging multiple JSON files using Python - Code Review Stack Exchange
I have multiple (1000+) JSON files each of which contain a JSON array. I want to merge all these files into a single file. I came up with the following, which reads each of those files and creates... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
April 17, 2015
What is the best way to merge two JSON file in Python?
You'll need to give a bit more information, ideally examples of the two docs and what you want the output to be. More on reddit.com
🌐 r/learnpython
8
5
May 2, 2024
Issue with merging multiple JSON files in Python - Stack Overflow
I am trying to combine multiple JSON files in a Ubuntu platform. As an example, the data from two files are as follows: File_1 { "artist":"Gob", "timestamp":"2011-08-09 01:59:41.352247", ... More on stackoverflow.com
🌐 stackoverflow.com
October 18, 2018
🌐
Medium
medium.com › @programinbasic › merge-multiple-json-files-into-one-in-python-65c009aad81d
Merge Multiple JSON files into One in Python | by ProgrammingBasic | Medium
January 17, 2024 - So this is how you can merge JSON files into one single file using Pythons’s built-in json modules or using Pandas library.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-merge-multiple-json-files-using-python
How to Merge Multiple JSON Files Using Python - GeeksforGeeks
July 23, 2025 - In this example, a Python function merge_json_files is defined to combine data from multiple JSON files specified by file_paths into a list called merged_data.
🌐
Medium
medium.com › @abdelfatahmennoun4 › how-to-combine-multiple-json-files-into-a-single-json-file-c2ed3dc372c2
How to Combine Multiple JSON Files into a Single JSON File | by Abdelfatah MENNOUN | Medium
May 19, 2023 - Here is an example of how to combine multiple JSON files into a single JSON file using Python: import json # Create a list of all the JSON files that you want to combine. json_files = ["file1.json", "file2.json", "file3.json"] # Create an empty ...
🌐
Microsoft Fabric Community
community.fabric.microsoft.com › t5 › Service › How-to-merge-multiple-JSON-files-into-one › td-p › 4005497
How to merge multiple JSON files into one - Microsoft Fabric Community
June 28, 2024 - import json # Create a list of all the JSON files that you want to combine. json_files = ["file1.json", "file2.json", "file3.json"] # Create an empty list to store the Python objects. python_objects = [] # Load each JSON file into a Python object. for json_file in json_files: with open(json_file, "r") as f: python_objects.append(json.load(f)) # Dump all the Python objects into a single JSON file.
Find elsewhere
Top answer
1 of 2
7
  1. First off, if you want reusability, turn this into a function. The function should have it's respective arguments.
  2. Secondly, instead of allocating a variable to store all of the JSON data to write, I'd recommend directly writing the contents of each of the files directly to the merged file. This will help prevent issues with memory.
  3. Finally, I just have a few nitpicky tips on your variable naming. Preferably, head should have a name more along the lines of merged_files, and you shouldn't be using f as an iterator variable. Something like json_file would be better.
2 of 2
1

This is essentially alexwlchan's comment spelled out:

Parsing and serializing JSON doesn't come for free, so you may want to avoid it. I think you can just output "[", the first file, ",", the second file etc., "]" and call it a day. If all inputs are valid JSON, unless I'm terribly mistaken, this should also be valid JSON.

In code, version 1:

def cat_json(outfile, infiles):
    file(outfile, "w")\
        .write("[%s]" % (",".join([mangle(file(f).read()) for f in infiles])))

def mangle(s):
    return s.strip()[1:-1]

Version 2:

def cat_json(output_filename, input_filenames):
    with file(output_filename, "w") as outfile:
        first = True
        for infile_name in input_filenames:
            with file(infile_name) as infile:
                if first:
                    outfile.write('[')
                    first = False
                else:
                    outfile.write(',')
                outfile.write(mangle(infile.read()))
        outfile.write(']')

The second version has a few advantages: its memory requirements should be something like the size of the longest input file, whereas the first requires twice the sum of all file sizes. The number of simultaneously open file handles is also smaller, so it should work for any number of files.

By using with, it also does deterministic (and immediate!) deallocation of file handles upon leaving each with block, even in python implementations with non-immediate garbage collection (such as pypy and jython etc.).

🌐
Reddit
reddit.com › r/learnpython › what is the best way to merge two json file in python?
r/learnpython on Reddit: What is the best way to merge two JSON file in Python?
May 2, 2024 -

Hello everyone,

I am trying to merge two JSON files, but I couldn't find any quick package that can do this. One file contains the base policy, while the other includes additional files for excluding special configurations.

My goal is to merge these two JSON files of AntiVirus policy, which contain arrays and numerous elements, without overwriting any data. I was wondering what the best approach would be to accomplish this.

If its element just uses the value of the other files.
If its array just append new elements.

What is best way to achieve this goal?

Thanks all

🌐
Softhints
softhints.com › merge-multiple-json-files-pandas-dataframe
How to Merge Multiple JSON Files with Python
January 18, 2024 - The last step is concatenating list of DataFrames into a single one by: pd.concat(dfs) dfs = [] for file in file_list: with open(file) as f: json_data = pd.json_normalize(json.loads(f.read())) json_data['site'] = file.rsplit("/", 1)[-1] dfs.append(json_data) df = pd.concat(dfs) If you like to have a trace of each record from which file is coming - then you can use a line like: ... Below you can find how to merge multiple JSON line files.
🌐
Python Forum
python-forum.io › thread-29128.html
Merge JSON Files
I want to incrementally merge multiple json files of similar structure into a single file that already exists. My code is: import glob read_files = glob.glob('/dbfs/mnt/sourton-house/File*.json') with open('/dbfs/mnt/sourton-house/mergedJsonFile....
🌐
Agentsfordata
agentsfordata.com › json tools › json merge
Merge JSON Files Online Free - Combine Multiple JSONs
Let's begin by installing the ClickHouse Connect library for Python: ... query = f""" CREATE TABLE merged_file AS SELECT * FROM file('path/to/file1.json', json) UNION ALL SELECT * FROM file('path/to/file2.json', json) """ client.command(query) ... export_query = f""" SELECT * FROM merged_file INTO OUTFILE 'path/to/merged_file.json' FORMAT json """ client.command(export_query)
🌐
Like Geeks
likegeeks.com › home › python › pandas › merge multiple json files in python using pandas
Merge Multiple JSON files in Python using Pandas
To use concat(), you first need to read each of your JSON files into separate DataFrames using read_json() function. Once you have your DataFrames, you can merge them using concat(). Here’s a step-by-step breakdown: Read Multiple JSON Files: ...
🌐
Bobby Hadz
bobbyhadz.com › blog › merge-json-files-in-python
How to merge multiple JSON files in Python [3 Ways] | bobbyhadz
June 20, 2023 - This is the main.py file that merges the two .json files into one. ... Copied!import json def merge_json_files(file_paths): merged_contents = [] for file_path in file_paths: with open(file_path, 'r', encoding='utf-8') as file_in: merged_contents.extend(json.load(file_in)) with open('employees_final.json', 'w', encoding='utf-8') as file_out: json.dump(merged_contents, file_out) paths = [ 'employees_1.json', 'employees_2.json' ] merge_json_files(paths) ... After running the python main.py command, the following employees_final.json file is produced.
🌐
Stack Overflow
stackoverflow.com › questions › 62581731 › how-to-merge-several-json-files-into-one-using-python
How to merge several json files into one using python - Stack Overflow
#!/usr/bin/env python """Read a list of JSON files holding a list of dictionaries and merge into a single JSON file holding a list of all of the dictionaries""" import sys import argparse import json def do_merge(infiles, outfile): merged = [] for infile in infiles: with open(infile, 'r', encoding='utf-8') as infp: data = json.load(infp) assert isinstance(data, list), "invalid input" merged.extend(data) with open(outfile, 'w', encoding="utf-8") as outfp: json.dump(merged, outfp) return 0 def main(argv): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('outfile', help="
🌐
Reddit
reddit.com › r/learnpython › help with merging multiple json files into single json file
r/learnpython on Reddit: Help with merging multiple JSON files into single JSON file
October 25, 2019 -

This is my first venture into anything Python and JSON. I'm receiving about 30 JSON files a day all stored in the same directory. I would like to be able to combine these JSON files into a single file nightly. Once I have the single file I will then flatten out the JSON file and convert to a CSV.

All of my JSON files are structured the same way regarding the objects that are included. I have been reading over many different ways to merge the JSON files with Python but have not had any luck yet.

Here is what I am currently trying to get to work and any help would be appreciated.

import glob
import json

result =[]
for f in glob.glob("*.json"):
    with open(f, "r") as infile:
        result.append(json.load(infile))

with open("merged_file.json", "w") as outfile:
    json.dump(result, outfile)

I then would run this code which does convert from JSON to CSV.

import json
import csv

def get_leaves(item, key=None):
    if isinstance(item, dict):
        leaves = {}
        for i in item.keys():
            leaves.update(get_leaves(item[i], i))
        return leaves
    elif isinstance(item, list):
        leaves = {}
        for i in item:
            leaves.update(get_leaves(i, key))
        return leaves
    else:
        return {key: item}

with open('test2.json') as f_input:
    json_data = json.load(f_input)

fieldnames = set()

for entry in json_data:
    fieldnames.update(get_leaves(entry).keys())

with open('output.csv', 'a', newline='') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames=sorted(fieldnames))
    csv_output.writeheader()
    csv_output.writerows(get_leaves(entry) for entry in json_data)

In a perfect world I would love to be able to have Python automate the process and run at 3 am daily. It would search the directory for any JSON files created over the last 24 hours and combine them into the single JSON file. Then convert the file to CSV.

If anyone cant assist I would appreciate it.

🌐
GitHub
gist.github.com › martinbeentjes › be134561f818ca05c8ada6ac27558e36
Merge json files into one json file · GitHub
Merge json files into one json file. GitHub Gist: instantly share code, notes, and snippets.