camelyellow
camelyellow

Reputation: 37

Append to json matching by key

I have json like this (no.1)

[
 {
   'id': 1,
   'data': '...'
 },
 {
   'id': 2,
   'data': '...'
 }
]

and i want to append into this other json which looks like (no.2)

[
 {
   'id': 1,
   'data_additional': '...'
 },
 {
   'id': 2,
   'data_additional': '...',
 }
]

and the output should look like: (no1 + no2)

[
 {
   'id': 1,
   'data': '...',
   'data_additional': '...'
 },
 {
   'id': 2,
   'data': '...',
   'data_additional': '...'
 }
]

how can i do this in python? i tried to do it using for loop, is there any other way to do this?

no3 = {}
if len(no1) == len(no2):
  for x in range(len(no1)):
    for y in range(len(no2)):
      if no1[x]['id'] == no2[y]['id']:
        no3[x].append({**no1[x], **no2[y]})

Upvotes: 0

Views: 253

Answers (2)

balderman
balderman

Reputation: 23815

something like the below (no need for an external library)

d1 = [
 {
   'id': 1,
   'data': 'WWW'
 },
 {
   'id': 2,
   'data': 'KKK'
 }
]

d2 = [
 {
   'id': 1,
   'data_additional': 'AAA'
 },
 {
   'id': 2,
   'data_additional': 'BBB',
 }
]
#
# assuming the lists are sorted by id
#
data = []
for idx,entry in enumerate(d1,):
    data.append(entry)
    data[-1].update(d2[idx])
print(data)

output

[{'id': 1, 'data': 'WWW', 'data_additional': 'AAA'}, {'id': 2, 'data': 'KKK', 'data_additional': 'BBB'}]

Upvotes: 1

MrMikimn
MrMikimn

Reputation: 851

You can do this with pandas' join method for simplicity and speed:

import pandas as pd

df1 = pd.DataFrame(json1).set_index('id')
df2 = pd.DataFrame(json2).set_index('id')

df1.join(df2).reset_index().to_dict(orient='records')

The set_index calls ensure that join will join records by id. reset_index makes sure that calling to_dict (to transform the data frame back to json) will also include the ids.

Upvotes: 1

Related Questions