How to Merge Multiple JSON Files Using Python
Last Updated :
28 Apr, 2025
We are given multiple JSON files and our task is to merge those multiple JSON files into a single JSON file with the help of different approaches in Python. In this article, we will see how we can merge multiple JSON files in Python.
JSON Files
Below are the two JSON files that we will use in our article to merge them into a single JSON file.
f.json
{"key1":"value1"}
s.json
{"key2": "value2"}
Merging Multiple JSON Files in Python
Below are some of the ways by which we can merge multiple JSON files in Python:
- Using json Module
- Using List Comprehension
- Using os Module with json Module
- Using glob Module with json Module
- Using Pandas Library
Merge Multiple JSON Files Using json Module
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
. The merged data is then written to a new JSON file named "merged.json," and a confirmation message is printed.
Python3
import json
def merge_json_files(file_paths, output_file):
merged_data = []
for path in file_paths:
with open(path, 'r') as file:
data = json.load(file)
merged_data.append(data)
with open(output_file, 'w') as outfile:
json.dump(merged_data, outfile)
file_paths = ["f.json", "s.json"]
output_file = "merged.json"
merge_json_files(file_paths, output_file)
print(f"Merged data written to '{output_file}'")
Output:
merged.json
[{"key1": "value1"}, {"key2": "value2"}]
Merge Multiple JSON Files Using List Comprehension
In this example, the merge_json_files
function reads JSON data from multiple files specified by file_paths
using a list comprehension. The data is then stored in a list named merged_data
. Subsequently, the combined data is written to a new JSON file, "merged.json," using the json.dump()
method. Finally, the merged data list is printed for confirmation.
Python
import json
def merge_json_files(file_paths):
merged_data = [json.load(open(path, 'r')) for path in file_paths]
return merged_data
file_paths = ["f.json", "s.json","e.json","t.json"]
output_file = "merged.json"
merged_data = merge_json_files(file_paths)
with open(output_file, 'w') as outfile:
json.dump(merged_data, outfile)
print(merged_data)
Output:
merged.json
[{"key1": "value1"}, {"key2": "value2"}, {"key2": "value2"}, {"key2": "value2"}]
Merge Multiple JSON Files Using os Module with json Module
In this example, the merge_json_files
function reads and merges JSON files from the specified directory ("./files"
). The combined data is then written to a new JSON file named "merged.json," and the merged data is printed for confirmation.
Python3
import json
import os
def merge_json_files(directory_path):
merged_data = []
for filename in os.listdir(directory_path):
if filename.endswith('.json'):
with open(os.path.join(directory_path, filename), 'r') as file:
data = json.load(file)
merged_data.append(data)
return merged_data
directory_path = "./files"
output_file = "merged.json"
merged_data = merge_json_files(directory_path)
with open(output_file, 'w') as outfile:
json.dump(merged_data, outfile)
print(merged_data)
Output:
merged.json
[{"key1": "value1"}, {"key2": "value2"}]
Merge Multiple JSON Files Using glob Module with json Module
In this example, the merge_json_files
function utilizes the glob
module to obtain a list of JSON file paths from the specified directory ("./files"
). It then reads and merges the JSON data from these files into a list named merged_data
. The combined data is subsequently written to a new JSON file, "merged.json," and the merged data is printed for confirmation.
Python3
import json
import glob
def merge_json_files(directory_path):
merged_data = []
file_paths = glob.glob(directory_path + '/*.json')
for path in file_paths:
with open(path, 'r') as file:
data = json.load(file)
merged_data.append(data)
return merged_data
directory_path = "./files"
output_file = "merged.json"
merged_data = merge_json_files(directory_path)
with open(output_file, 'w') as outfile:
json.dump(merged_data, outfile)
print(merged_data)
Output:
merged.json
[{"key1": "value1"}, {"key2": "value2"}]
Merge Multiple JSON Files Using Pandas Library
In this example, the merge_json_files
function reads JSON data from multiple files specified by file_paths
and merges them into a Pandas DataFrame named merged_data
. The combined data is then written to a new JSON file, "merged.json," using the to_json
method with the 'records' orientation. Finally, the merged DataFrame is printed for confirmation.
Python3
import pandas as pd
import json
def merge_json_files(file_paths):
merged_data = pd.DataFrame()
for path in file_paths:
with open(path, 'r') as file:
data = json.load(file)
row = pd.DataFrame([data])
merged_data = pd.concat([merged_data, row], ignore_index=True)
return merged_data
file_paths = ["f.json", "s.json", "e.json", "t.json"]
output_file = "merged.json"
merged_data = merge_json_files(file_paths)
merged_data.to_json(output_file, orient='records')
print(merged_data)
Output:
merged.json
[{"key1": "value1", "key2": null}, {"key1": null, "key2": "value2"}, {"key1": null, "key2": "value2"}, {"key1": null, "key2": "value2"}]
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read