How to merge two JSON files in Python

Hello Learners, today we are going to learn how to merge two JSON files in Python. Let’s see what do you know about JSON?

JSON – JavaScript Object Notation

What is a JSON file?

JSON is a file format that is used to store JavaScript objects. Now the question comes “What is a JavaScript object?”

A JavaScript object is a collection of unordered Key-Value pairs. An example of a JSON file is given below:

How to merge two JSON files in Python

How to merge two JSON files in Python

Here, we have 3 different files of .json type so without wasting any time let’s jump into the code to see the implementation.

Merge two JSON files without using a third file in Python

There are other methods to do this also. You can do it by importing json library but it would be a little complex for beginners who have no idea about json objects and Python dictionary. So, here we will do it using basic File Handling in Python as it will be much easier for you!

Without wasting time see the code given below:

f2data = "" 

with open('C:\\Users\\lenovo\\Documents\\file2.json') as f2: 
  f2data = '\n' + f2.read()
    
with open('C:\\Users\\lenovo\\Documents\\file1.json','a+') as f1:
    f1.write(f2data)

OUTPUT:

Merge two JSON files without using a third file in Python

Merging two JSON files into a third file

As you have seen the image on the top, we have three JSON files and the third file ‘file3.json‘ is empty now. Let’s see what will happen after the execution of code!

f1data = f2data = "" 
 
with open('C:\\Users\\lenovo\\Documents\\file1.json') as f1: 
  f1data = f1.read() 

with open('C:\\Users\\lenovo\\Documents\\file2.json') as f2: 
  f2data = f2.read() 
 
f1data += "\n"
f1data += f2data

with open ('C:\\Users\\lenovo\\Documents\\file3.json', 'a') as f3: 
  f3.write(f1data)

OUTPUT:

Merging two JSON files into a third file

  • In this code, we have opened the files in ‘read’ mode (which is by default) whose content we want to add in the other file.
  • In both codes, we have opened file 1 and file 3 in the append mode(‘a’) respectively. Don’t you think why we didn’t use the write mode(‘w’)? If you will use write mode, it’ll replace all the existing data in the file and if you don’t want to erase the existing data you should go for append mode.
  • In Python, we don’t have to think about the number of lines in the file unlike java or other languages. When you call the read method on file object like f1, f2, f3 etc, and assign it to another variable it will assign all the data of the file to that variable.

Click here to learn more about File Handling in Python.

So, that’s all for now about how to merge two JSON files in Python, till then Keep Learning, Keep Practicing, Keep Reading!

“THINK TWICE CODE ONCE!”

Leave a Reply

Your email address will not be published. Required fields are marked *