I am trying to merge "n" number of json files but i need to first load json from filepath and then use it. I referred below link but they already have json data available but in my case i want to first load json data in loop and then merge it. I am looking for generic way of doing it.
How do I merge a list of dicts into a single dict?
My code: I want to first load json data for all the files and then merge it. I am trying something like below but it does not work and give error as TypeError: str , bytes or ospath.like object, not Tuple
def merge_JsonFiles(*file):
result = {}
for f in file:
json_data = loadjson(file)
result = {**json_data}
return result
merge_JsonFiles(file1, file2, file3)
def loadjson(file)
with open(file , 'r') as fh:
return json.load(fh)
Merge logic for two files = {**file1, **file2)
4
Answers
I resolved it using below code
You send
tuple
type inopen
function and reasonably get and error. The problem is inmerge_JsonFiles
funtion in t linejson_data = loadjson(file)
,there instead ofloadjson(file)
you need to useloadjson(f)
, and then it’s all gonna work.It looks like there are a few issues with your code. Let’s go through them and provide a corrected version of the
merge_JsonFiles
function:loadjson
function is missing a colon (:) at the end of its definition.merge_JsonFiles
function is not using theloadjson
function correctly. You should pass the file path (f
) to theloadjson
function instead of passing the tuple of all files (file
).result
dictionary, you should be updating it with each loaded JSON data.Here’s the corrected version of your code:
In this corrected version, the
merge_JsonFiles
function now takes a variable number of file paths (*files
) and iterates through each file. It loads the JSON data from each file using theloadjson
function and then updates theresult
dictionary with the loaded JSON data using theupdate()
method. This way, the data from all files will be merged into a single dictionary.In this code,
merge_JsonFiles
function takes an arbitrary number of file paths as arguments. It then loads each JSON file one by one using the loadjson function and merges them into one dictionary. Finally, the merged dictionary is returned.