Hamza
Hamza

Reputation: 6045

How to separate json with lists as values into separate json objects with python?

So, I am trying to achieve the following. I have a json with following structure:

json = {'key1':[value11,value12], 'key2':[value12, value22]}

I want to separate each value in particular key to from a separate json while retaining its key as follows:

json1 = {'key1':value11,'key2':value12}
json2 = {'key1':value12,'key2':value22}

Builtin json module does not seems to help

Upvotes: 0

Views: 425

Answers (1)

Brizar
Brizar

Reputation: 131

Its hacky and I could not figure out to use the inline for loops, but it works for me: I first created the empty array, and due to the for loops you should be able to catch the case if sth should be none...

json = {'key1':[11, 12], 'key2':[21, 22]}
max_len = max([len(json[key]) for key in json.keys()])
data = [{}] * max_len
# data = [{} for _ in range(max_len)]
for i in range(max_len):
    for key in json.keys():
        data[i][key] = json[key][i] if json[key][i] else None
print(data)

gives:

[{'key1': 11, 'key2': 21}, {'key1': 12, 'key2': 22}]

Upvotes: 1

Related Questions