Combining Multiple JSON Files Into A Single JSON File
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is based on a subset of JavaScript language (the way objects are built-in JavaScript). JSON is often used when data is sent from a server to a web page so that JSON data processing in data analytics becomes inevitable.
In this article, I will show you an example of JSON data processing. The goal is to make JSON files containing one observation per file in a folder combined into a single JSON file. The advantage of performing this kind of data processing is you can significantly shrink your data size and simplify your data form so that it will be easier for somebody to use it.
Dataset
Imagine you received a folder of movie datasets, all in JSON type format. You will need to do an ETL process on those datasets, i.e. clean and store them into a data warehouse. But then you found that the folder is quite large.
Keeping data in such form and apply a usual pandas-data-processing in Python, you will be likely to have this kind of error:
The error is showing that you have run out of memory in your RAM when executing the codes. Fortunately, you can shrink the file size of the datasets by combining those movie JSON files into a single movies JSON file. A single JSON file also acts as a data warehouse for reproducible data analysis.
ETL Process
This is the form of a movie JSON file in the folder.
We can see that it is just a line of a dictionary, showing one movie data. Some of the fields are relevant for data analysis, some of them are not. We want to combine all movie observations into a single JSON file by picking necessary fields of a movie then put that in one line, then for the next movie we put that in the next line and so on. But before we dump the data, we need to do the transformation on some fields such as genres and spoken_language . The whole processes of extract, transform and load can be done in less than 40 lines of code (might be lesser, comment if you can find!). The code is as follows.
Here I use os.walk to extract data from the movies folder. Then by iterating the stored filenames, the data transformation on the genre and spoken_language column is running. The transformed data then stored in a predefined empty list called data_list . After the iteration is done, then by using json.dump we will be putting the data_list in a single JSON file, resulting in this output:
After movies.json created, we can see that the file size decreased from 452 MB to around 145 MB, 67% of memory is freed without losing any information! Besides, now we have a more centred data source that can be processed easier.
Conclusion
It is better to combine a folder full of JSON files into a single JSON file. The example above shows that the process gives you more space in your memory. Also, it will ease your data processing as you will not need to iterate over files in a folder. If you’re interested in this kind of data processing, don’t hesitate to visit my GitHub page. There you can find the details of the codes and clone my repository if you want to try it.
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:


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:
OUTPUT:

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!
OUTPUT:

- 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!
One response to “How to merge two JSON files in Python”
dude, this example is for combining json, not merging … The expected result of merging files is the following :
fruit: [
Cемантическое слияние JSON файлов в Git
Операция слияния (merge), выполняемая стандартными средствами git, хорошо работает для текстовых файлов, содержащих исходные тексты программ. Но слияние текстовых файлов, содержащих жестко структурированные данные, в частности JSON — это большая головная боль.
Для решения этой проблемы можно подключить к git’у отдельный инструмент слияния для JSON-файлов, который не работает построчно, а учитывает структуру JSON-объектов.
Предлагаю использовать для этого скрипт на javascript, который анализирует сливаемые JSON-файлы и делает слияние на основании структуры и вложенности объектов JSON.
Что это дает?
К примеру вы держите настройки своего приложения в JSON-файле. Если одновременно два разработчика добавят в конец файла новый параметр (каждый со своим именем), то при слиянии в git возникнет конфликт. Скрипт семантического слияния разберется, что добавлены два разных параметра и проведет слияние автоматически и без конфликтов, включив в результирующий файл оба параметра.
Также семантическое слияние спасает, когда в JSON хранятся списки объектов с одинаковым набором свойств. Если в середину такого списка добавлен новый объект, у которого от окружающих отличаются лишь несколько значений свойств, стандартный git’овский merge, да и любой инструмент построчного сравнения скорее всего запутается. Разрешать конфликт придется вручную, внимательно вглядываясь в текст и рискуя испортить структуру JSON.
То же касается и изменения порядка следования объектов в JSON.
Особенности семантического слияния
Порядок следования именованных объектов в файлах игнорируется.
Для неименованных объектов (элементов массива) порядок строк имеет значение. Сравнение массивов идет по порядку следования элементов массива в обоих файлах. При добавлении элемента в середину массива, такая ситуация не распознается и возникают конфликты во всех последующих элементах. Также конфликты возникают и при добавлении в конец массива элементов в обоих сливаемых файлах.
Конфликты
В случае конфликта (один и тот же объект изменен в обоих сливаемых версиях файла), в результирующий файл слияния добавляется информация, показывающая суть конфликта:
Версии скрипта
Поскольку мы разрабатываем windows-приложение и используем git под windows, то мне пришлось допилить скрипт, чтобы он работал на windows «из коробки», то есть через Windows Scripting Host. WSH не поддерживает JSON, поэтому библиотека разбора JSON включена прямо в скрипт. Для тех, кто готов использовать node.js имеется более компактная версия скрипта.
Инструкция по включению merge-драйвера в git
1. Кладем скрипт jsonmerge.js в папку git\lib, например в %Program Files (x86)%\Git\lib\
2. Подключаем в git новый merge-driver. Для этого вносим изменения в файл конфигурации git.
Для включения драйвера только для одного репозитория вносим изменения в файл <папка проекта>\.git\confg
Или, для включения драйвера для всех локальных репозиториев, вносим изменения в файл глобальный файл настроек .gitconfig, который лежит в папке профиля пользователя (в windows это %userprofile%), например C:\Users\<имя пользователя>\.gitconfig
Для node.js строка driver выглядит так:
Не забываем изменить путь к файлу jsonmerge.js на свой.
3. Указываем, для каких расширений файлов применять данный драйвер в файле .gitattributes. Его можно расположить в любой папке проекта, чтобы распространить его действие на папки нижнего уровня. Обычно находится в корневой папке проекта:
Изначально скрипт на coffeescript был взят отсюда, переведен на чистый javacript и доработан, чтобы его можно было запускать в windows через стандартный Windows Script Host. Также добавлена обработка ошибок: если JSON-структура одного из сливаемых файлов некорректная, оригинальный скрипт не возвращает признак конфликта, и git считает слияние успешным. В моем версии это исправлено.
How to merge 2 JSON objects from 2 files using jq?
I’m using the jq tools (jq-json-processor) in shell script to parse json.
I’ve got 2 json files and want to merge them into one unique file
Here the content of files:
file1
file2
expected result
I try a lot of combinations but the only result i get is the following, which is not the expected result:
Using this command:
8 Answers 8
Since 1.4 this is now possible with the * operator. When given two objects, it will merge them recursively. For example,
Important: Note the -s (—slurp) flag, which puts files in the same array.
If you also want to get rid of the other keys (like your expected result), one way to do it is this:
Or the presumably somewhat more efficient (because it doesn’t merge any other values):
This reads all JSON texts from stdin into an array ( jq -s does that) then it «reduces» them.
( add is defined as def add: reduce .[] as $x (null; . + $x); , which iterates over the input array’s/object’s values and adds them. Object addition == merge.)
Here’s a version that works recursively (using * ) on an arbitrary number of objects:
Who knows if you still need it, but here is the solution.
Once you get to the —slurp option, it’s easy!
Then the + operator will do what you want:
(Note: if you want to merge inner objects instead of just overwriting the left file ones with the right file ones, you will need to do it manually)
![]()
No solution or comment given so far considers using input to access the second file. Employing it would render unnecessary the buildup of an additional structure to extract from, such as the all-embracing array when using the —slurp (or -s ) option, which features in almost all of the other approaches.
To merge two files on top level, simply add the second file from input to the first in . using + :
To merge two files recursively on all levels, do the same using * as operator instead:
That said, to recursively merge your two files, with both objects reduced to their value field, filter them first using
Note that a solution which reduces only after the merge, like . * input |
In order to operate on more than two files, either accordingly use input multiple times, or programmatically iterate over all of them using inputs instead, as in