0

I have a huge json file as follows,

{"id": "KA88457","name": "Steven", "phone":"+6590876589"},
{"id": "KA88457", "fax": ["+6563323248"], "email":"[email protected]"}

I need to merge the two and obtain the desired result as

{"id": "KA88457",
 "name": "Steven", 
 "phone":"+6590876589", 
 "fax":["+6563323248"], 
 "email":"[email protected]"}

I checked online but I was able to find only merging two json files in python. Can you please help to in merging these type of records using python.

2 Answers 2

1

Python dictionaries have a .update() method, which can also be used for your situation. It is used to update the original dict to include the changes or addition from the second dict.

first_dict={"id": "KA88457","name": "Steven", "phone":"+6590876589"}
second_dict={"id": "KA88457", "fax": ["+6563323248"], "email":"[email protected]"}
first_dict.update(second_dict)
print(first_dict)

Output:

{'id': 'KA88457', 'name': 'Steven', 'phone': '+6590876589', 'fax': ['+6563323248'], 'email': '[email protected]'}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. But I have a doubt. 1. The file is very big. How will I be able to know first_dict has to append with second_dict ? May be I use loop to check if it has similar id, it has to append and remove duplicates. Is there any other solution ? 2. How can I assign those each dictionary to a new variable like first_dict and second_dict ? Sorry to bother with silly questions
0

Assuming you know how to convert the strings from json to a python dictionary object (see json module) you can 'merge' them in the way you describe, with the following:

objOne = {"id": "KA88457","name": "Steven", "phone":"+6590876589"}
objTwo = {"id": "KA88457", "fax": ["+6563323248"], "email":"[email protected]"}

for key in objOne:
    objTwo[key] = objOne[key]

This should take all the properties of objOne and add them to objTwo.

4 Comments

So you mean, I have to convert them to strings and then use json module called merge ? Also the file size is too huge. I'm new to python. So, I'm confused on how to proceed.
The above is already a dictionary right ? Please correct me if I'm wrong.
Those are dictionary objects. But if you read them in from a file, they'll come in as strings, and you'll need to parse them into a dictionary object.
Oh okay. I'm reading them from a file. So which means i need to parse them. I shall give a try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.