Home > Enterprise >  Json with multiple values under single key to json array python
Json with multiple values under single key to json array python

Time:02-02

I want to convert Json which is in this form

{'number':[1,2,3,3],'addr':['a',b","c","d"]}

I want json in this form

[{'number':1,'addr':'a'},{'number':2,'addr':'b'},{'number':3,'addr':'c'},{'number':3,'addr':'d'}]

I have tried to search this in all platform but couldn't find anything

CodePudding user response:

All you need to do is create a new list, iterrate the length of the sublist and and add a new dictionary for each key,value pair and add it to the empty list.

current = {'number':[1,2,3,3],'addr':['a',"b","c","d"]}
lst = []
num_elem = len(current['number'])
for i in range(num_elem):
    item = {k:current[k][i] for k in current.keys()}
    lst.append(item)

or if you want an unreadable oneliner:

[{i:current[i][k],j:current[j][k]} for i,j in [current.keys()] for k in range(len(current[i]))]

OUTPUT:

[{'number': 1, 'addr': 'a'},
 {'number': 2, 'addr': 'b'},
 {'number': 3, 'addr': 'c'},
 {'number': 3, 'addr': 'd'}]
  • Related