As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

EDIT 2 Nov 2024: Pretty sure we can now do merged = dictA | dictB

Answer from P i 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
Top answer
1 of 6
45

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

EDIT 2 Nov 2024: Pretty sure we can now do merged = dictA | dictB

2 of 6
39

Assuming a and b are the dictionaries you want to merge:

c = {key: value for (key, value) in (a.items() + b.items())}

To convert your string to python dictionary you use the following:

import json
my_dict = json.loads(json_str)

Update: full code using strings:

# test cases for jsonStringA and jsonStringB according to your data input
jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'
jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)

# now we have two json STRINGS
import json
dictA = json.loads(jsonStringA)
dictB = json.loads(jsonStringB)

merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}

# string dump of the merged dict
jsonString_merged = json.dumps(merged_dict)

But I have to say that in general what you are trying to do is not the best practice. Please read a bit on python dictionaries.


Alternative solution:

jsonStringA = get_my_value_as_string_from_somewhere()
errors_dict = json.loads(jsonStringA)

new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)
new_error_key = "error_%d" % (timestamp_number)

errors_dict[new_error_key] = new_error_str

# and if I want to export it somewhere I use the following
write_my_dict_to_a_file_as_string(json.dumps(errors_dict))

And actually you can avoid all these if you just use an array to hold all your errors.

Discussions

python - Combining two JSON objects in to one - Stack Overflow
I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a si... More on stackoverflow.com
🌐 stackoverflow.com
is it possible merge two json object
some function like this json1.join(json2) or json1.merge(json2) or json1 += json2 More on github.com
🌐 github.com
14
January 15, 2017
Merge two json object in python - Stack Overflow
In json module, dumps convert python object to a string, and loads convert a string into python object. So in your original codes, you just try to concat two json-string. Try to code like this: import json from collections import defaultdict def merge_dict(d1, d2): dd = defaultdict(list) for ... More on stackoverflow.com
🌐 stackoverflow.com
May 2, 2021
Python - Combining two json objects - Stack Overflow
I am trying to follow the answer(s) in the question shown here, but I'm still having some trouble combining my two json objects. I have two JSON objects which are returned from a web call and I'm More on stackoverflow.com
🌐 stackoverflow.com
August 24, 2012
🌐
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

🌐
AskPython
askpython.com › home › what is json and how to merge two json strings?
What Is JSON and How To Merge Two Json Strings? - AskPython
March 16, 2023 - These two dictionaries are merged using the merge method of the jsonmerge library. This merged dictionary is stored in a variable called merg. This dictionary is passed as an argument to the jsonloads() method, which returns a JSON object.
🌐
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 - It opens a new file called ... data1 dict as JSON to the output file. Another way to merge JSON in Python is by using the pandas library....
🌐
Bobby Hadz
bobbyhadz.com › blog › merge-two-json-objects-in-python
How to merge two JSON objects in Python [5 Ways] | bobbyhadz
April 11, 2024 - Copied!import json obj1 = json.dumps({'id': 1, 'name': 'bobby hadz'}) obj2 = json.dumps({'site': 'bobbyhadz.com', 'topic': 'Python'}) dict1 = json.loads(obj1) dict2 = json.loads(obj2) merged_dict = {**dict1, **dict2} print(merged_dict) with open('data.json', 'w', encoding='utf-8') as f: json.dump(merged_dict, f) ... We used the with statement to open a data.json file for writing. The json.dump() method serializes the supplied object as a JSON formatted stream and writes it to a file.
🌐
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 - 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.
🌐
Programmingbasic
programmingbasic.com › merge-multiple-json-objects-into-one-single-object-python
Merge multiple JSON objects into one single object in Python
March 27, 2025 - Combine multiple JSON objects from a file into a single object and then save it in a file in python.
Find elsewhere
🌐
GitHub
github.com › nlohmann › json › issues › 428
is it possible merge two json object · Issue #428 · nlohmann/json
January 15, 2017 - some function like this json1.join(json2) or json1.merge(json2) or json1 += json2
Author   itviewer
🌐
pytz
pythonhosted.org › json-merger › _modules › json_merger › merger.html
json_merger.merger — json-merger 0.2.2 documentation
"""Definition for JSON merger class.""" from __future__ import absolute_import, print_function import copy from .comparator import DefaultComparator from .dict_merger import SkipListsMerger from .errors import MergeError from .list_unify import ListUnifier from .utils import ( get_conf_set_for_key_path, get_dotted_key_path, get_obj_at_key_path, set_obj_at_key_path ) PLACEHOLDER_STR = '#$PLACEHOLDER$#' [docs]class Merger(object): """Class that merges two JSON objects that share a common ancestor.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-merge-multiple-json-files-using-python
How to Merge Multiple JSON Files Using Python - GeeksforGeeks
April 28, 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. Below are the two JSON files that we will use in our article ...
🌐
Like Geeks
likegeeks.com › home › python › 8+ examples for merging json arrays in python
8+ Examples for Merging JSON arrays in Python
February 8, 2024 - There are two basic ways to merge simple JSON arrays, shallow copy using + operator and deep copy using copy module. A shallow copy means the merged array contains references to the original objects.
🌐
CodeSpeedy
codespeedy.com › home › how to merge two json files in python
Merge two different JSON files in Python - CodeSpeedy
March 12, 2020 - 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)
🌐
CopyProgramming
copyprogramming.com › howto › how-to-merge-two-json-string-in-python
Python: Combining Two JSON Strings in Python: A Guide
April 21, 2023 - The json module provides two methods for converting Python objects to strings and strings to Python objects. Therefore, instead of simply concatenating two json-string in your original code, try coding in the following manner: import json from collections import defaultdict def merge_dict(d1, d2): dd = defaultdict(list) for d in (d1, d2): for key, value in d.items(): if isinstance(value, list): dd[key].extend(value) else: dd[key].append(value) return dict(dd) if __name__ == '__main__': json_str1 = json.dumps({"a": [1, 2]}) json_str2 = json.dumps({"a": [3, 4]}) dct1 = json.loads(json_str1) dct2 = json.loads(json_str2) combined_dct = merge_dict(dct1, dct2) json_str3 = json.dumps(combined_dct) # {"a": [1, 2, 3, 4]} print(json_str3)
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.).