-1

I have written below logic to merge two json files in python, it works perfectly fine. Now, I want to pass only one parameter to the method "filename" and i can pass "n" number of files and they should be able to merge. How i can apply that "forloop" and merge all json ?

def merge_JsonFiles(file1, file2):
   first_json = load_json(file1)
   second_json = load_json (file2)
   merge_json = {**first_json, **second_json}
   return merge_json
Bokambo
  • 4,204
  • 27
  • 79
  • 130

1 Answers1

1

Use star-operator (argument unpacking) consider following function which merge dicts

d1 = {"x":1}
d2 = {"y":2}
d3 = {"z":3}
def merge(*args):
    result = {}
    for a in args:
        result = {**result, **a}
    return result
print(merge(d1,d2,d3))

output

{'x': 1, 'y': 2, 'z': 3}
Daweo
  • 31,313
  • 3
  • 12
  • 25
  • Please note that the parameters to the method are filepath strings (after loading the file path it has json) they are not json , it gives me error 'str' object is not mapping – Bokambo Jul 26 '23 at 10:28