Home > database >  Merge three json result into one json
Merge three json result into one json

Time:07-27

I have these three json file:

First:

[
    {
        "amount": 100,
        "id": 1
    }
]

Second:

[
    {
        
        "new_id": 0,
        "id": 1,
        "date": 01/01/2023
    }
]

Third:

[
    {
        
        "new_id": 0,
        "start_date": 01/01/2024
    }
]

I want to merge these three json response together, the ideal result should be:

Final:

[
    {
        "amount": 100,
        "new_id": 0,
        "id": 1,
        "date": 01/01/2023
        "start_date": 01/01/2024

    }
]

I tried the method of update and update the first and second using a dict(hashmap). Is there a way to do this all together? by depending on two field "id" and "new_id"?

merged = {}

with open('File1.json') as f:
    for line in f:
        jsonified = json.loads(line)
        merged[jsonified['id']] = jsonified

with open('File2.json') as f:
    for line in f:
        jsonified = json.loads(line)
        merged[jsonified['id']].update(jsonified)

CodePudding user response:

maybe this:

import json

res = {}
for file in ["1.json", "2.json", "3.json"]:
    with open(file) as f:
        res.update(json.load(f)[0])

print(res)

# {'amount': 100, 'id': 1, 'new_id': 0, 'date': '01/01/2023', 'start_date': '01/01/2024'}

  • Related