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
This Python module allows you to merge a series of JSON documents into a single one.
      » 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.

🌐
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....
🌐
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

🌐
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.
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.).

🌐
Bobby Hadz
bobbyhadz.com › blog › merge-two-json-objects-in-python
How to merge two JSON objects in Python [5 Ways] | bobbyhadz
Copied!import json obj1 = ... hadz', 'site': 'bobbyhadz.com'} print(merged_dict) ... Use the json.loads() method to parse the JSON objects into Python dictionaries....
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-merge-multiple-json-files-using-python
How to Merge Multiple JSON Files Using Python - GeeksforGeeks
July 23, 2025 - Below are the two JSON files that ... ... 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....
🌐
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.
Find elsewhere
🌐
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 - Suppose you are working on your ... JSON object documents. You might want to combine all of them into one structure so it would be easy to locate the data. Merging JSON strings will come in handy in data management. We can merge multiple json strings into one single entity. We are going to look at the following examples. ... In this example, we are going to see the usage of jsonmerge library of the PyPI repository. PyPI is the third-party repository for python ...
Top answer
1 of 2
1

If your records are stored separated by newlines in a text file I would recommend the following approach by opening the file, parsing the records, and adding them to a dict which you can later dump with the native json library.

import json
data = {'records': []}

with open("data.txt", 'r') as f:
    lines = f.readlines()
    for line in lines:
        data['records'].append(json.loads(line))
        
print(json.dumps(data))
2 of 2
0

I would do it following way, let file.txt content be

{"eventVersion":"1.08","userIdentity":{"type":"AssumedRole","principalId":"AA:i-096379450e69ed082","arn":"arn:aws:sts::34502sdsdsd:assumed-role/RDSAccessRole/i-096379450e69ed082","accountId":"34502sdsdsd","accessKeyId":"ASIAVAVKXAXXXXXXXC","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"AROAVAVKXAKDDDDD","arn":"arn:aws:iam::3450291sdsdsd:role/RDSAccessRole","accountId":"345029asasas","userName":"RDSAccessRole"},"webIdFederationData":{},"attributes":{"mfaAuthenticated":"false","creationDate":"2021-04-27T04:38:52Z"},"ec2RoleDelivery":"2.0"}},"eventTime":"2021-04-27T07:24:20Z","eventSource":"ssm.amazonaws.com","eventName":"ListInstanceAssociations","awsRegion":"us-east-1","sourceIPAddress":"188.208.227.188","userAgent":"aws-sdk-go/1.25.41 (go1.13.15; linux; amd64) amazon-ssm-agent/","requestParameters":{"instanceId":"i-096379450e69ed082","maxResults":20},"responseElements":null,"requestID":"a5c63b9d-aaed-4a3c-9b7d-a4f7c6b774ab","eventID":"70de51df-c6df-4a57-8c1e-0ffdeb5ac29d","readOnly":true,"resources":[{"accountId":"34502914asasas","ARN":"arn:aws:ec2:us-east-1:3450291asasas:instance/i-096379450e69ed082"}],"eventType":"AwsApiCall","managementEvent":true,"eventCategory":"Management","recipientAccountId":"345029149342"}
{"eventVersion":"1.08","userIdentity":{"type":"AssumedRole","principalId":"AROAVAVKXAKPKZ25XXXX:AmazonMWAA-airflow","arn":"arn:aws:sts::3450291asasas:assumed-role/dev-1xdcfd/AmazonMWAA-airflow","accountId":"34502asasas","accessKeyId":"ASIAVAVKXAXXXXXXX","sessionContext":{"sessionIssuer":{"type":"Role","principalId":"AROAVAVKXAKPKZXXXXX","arn":"arn:aws:iam::345029asasas:role/service-role/AmazonMWAA-dlp-dev-1xdcfd","accountId":"3450291asasas","userName":"dlp-dev-1xdcfd"},"webIdFederationData":{},"attributes":{"mfaAuthenticated":"false","creationDate":"2021-04-27T07:04:08Z"}},"invokedBy":"airflow.amazonaws.com"},"eventTime":"2021-04-27T07:23:46Z","eventSource":"logs.amazonaws.com","eventName":"CreateLogStream","awsRegion":"us-east-1","sourceIPAddress":"airflow.amazonaws.com","userAgent":"airflow.amazonaws.com","errorCode":"ResourceAlreadyExistsException","errorMessage":"The specified log stream already exists","requestParameters":{"logStreamName":"scheduler.py.log","logGroupName":"dlp-dev-DAGProcessing"},"responseElements":null,"requestID":"40b48ef9-fc4b-4d1a-8fd1-4f2584aff1e9","eventID":"ef608d43-4765-4a3a-9c92-14ef35104697","readOnly":false,"eventType":"AwsApiCall","apiVersion":"20140328","managementEvent":true,"eventCategory":"Management","recipientAccountId":"3450291asasas"}

then

with open('file.txt', 'r') as f:
    jsons = [i.strip() for i in f.readlines()]
with open('total.json', 'w') as f:
    f.write('{"Records":[')
    f.write(','.join(jsons))
    f.write(']}')

will produce total.json with desired shape and being legal JSON if every line inside file.txt is legal JSON.

🌐
Like Geeks
likegeeks.com › home › python › 8+ examples for merging json arrays in python
8+ Examples for Merging JSON arrays in Python
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.
🌐
Like Geeks
likegeeks.com › home › python › pandas › merge multiple json files in python using pandas
Merge Multiple JSON files in Python using Pandas
Pandas provides the merge() function for combining DataFrames based on specific keys, similar to SQL join operations. It allows various types of joins (like inner, outer, left, right) and enables you to specify one or more keys to merge on.
🌐
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)