1

I'm new to python. Can anyone help in solving this problem? I have this problem to merge json a and json b using unique id

a = [{'id': 1, 'name': 'a', 'e_data': {'reading':'', 'writing':''}},
    {'id': 2, 'name': 'b', 'e_data': {'reading':'', 'writing':''}}]

b = [{'id':1,'reading':'2','writing':'3'}, 
    {'id':2,'reading':'3','writing':'3'}]

Output

[{'id': 1,'name': 'a','e_data':{'reading':'2','writing':'3'}},{'id': 2,'name': 'b','e_data':{'reading':'3','writing':'3'}}]

2 Answers 2

1

Try this.

a = [{'id': 1, 'name': 'a', 'e_data': {'reading':'', 'writing':''}},
    {'id': 2, 'name': 'b', 'e_data': {'reading':'', 'writing':''}}]

b = [{'id':1,'reading':'2','writing':'3'},
    {'id':2,'reading':'3','writing':'3'}]

for i in a:
    for j in b:
        if j['id'] == i['id']:
            i['e_data'].update(j)
            i['e_data'].pop('id')

print(a)

Output:

[{'id': 1, 'name': 'a', 'e_data': {'reading': '2', 'writing': '3'}}, {'id': 2, 'name': 'b', 'e_data': {'reading': '3', 'writing': '3'}}]
Sign up to request clarification or add additional context in comments.

Comments

0

Here is one simple way:

a = [{'id': 1, 'name': 'a', 'e_data': {'reading':'', 'writing':''}},
    {'id': 2, 'name': 'b', 'e_data': {'reading':'', 'writing':''}}]

b = [{'id':1,'reading':'2','writing':'3'}, 
    {'id':2,'reading':'3','writing':'3'}]

for dest in a:
    for source in b:
        if source['id'] == dest['id']:
            dest['e_data'].update(source)
a  

#[{'e_data': {'id': 1, 'reading': '2', 'writing': '3'}, 'id': 1, 'name': 'a'},
#{'e_data': {'id': 2, 'reading': '3', 'writing': '3'}, 'id': 2, 'name': 'b'}]

Comments

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.