How To Merge Multiple Json Files Into One In Python

Merging multiple JSON files into one is a common task in Python when working with large datasets or different data sources. By combining data from multiple files into a single file, you can better manage your data and analyze it for insights. In this tutorial, we will learn how to merge multiple JSON files into one using Python.

Step 1: Create a list of JSON files

First, we need to create a list of JSON file names that we want to merge. For demonstration purposes, let’s consider we have two JSON files named file1.json and file2.json.

Step 2: Read and parse JSON files

Next, we need to read the JSON files, parse them using Python’s built-in JSON library, and store the parsed data in a dictionary.

Step 3: Merge JSON files

Now, we can merge the data in the json_data list into a single JSON object.

This code snippet assumes that each JSON file has a dictionary with unique keys that store a list of values. If there’s a key present in both files, their values get combined into one list.

Step 4: Save the merged data to a new JSON file

Finally, we can save the merged data to a new JSON file.

Full Code

The following is the complete code for merging multiple JSON files into one in Python.

For the above code, let’s assume the content of the two JSON files is as follows:

file1.json:

file2.json:

Output

Upon running this script, a new file called merged_data.json will be created with the following content:

{
    "data1": [1, 2, 3, 7, 8, 9],
    "data2": [4, 5, 6, 10, 11, 12]
}

Conclusion

In this tutorial, we have learned how to merge multiple JSON files into one in Python using the built-in JSON library. By merging JSON files, you can efficiently manage your data and perform analysis on the consolidated data.