Satheesh Panduga
Satheesh Panduga

Reputation: 818

Convert json to array in python (value,id,value,id....)

Am trying to create an array from json object, I can print the required values but couldn't push them into array in Python, how can I do that?

data={"wc":[{"value":8,"id":0},{"value":9,"id":1}]}

dataset = []
test=[]

for i in data['wc']:
    print(i['value'],',',i['id'])
    test=i['value'],i['id']
    dataset.append(test)

print(dataset)

Am getting correct values as required but with '(' and ')' How can I remove them and get final output as

[8,0,9,1]

Like [value,id,value,id....]

Upvotes: 0

Views: 224

Answers (1)

Mike Müller
Mike Müller

Reputation: 85482

You already have a nested dictionary. Just iterate over the values of the nested dicts:

dataset = []
for entry in data['wc']:
    for value in entry.values():
        dataset.append(value)

>>> dataset
[0, 8, 1, 9]

with order value first id second:

dataset = []
for entry in data['wc']:
    dataset.extend([entry['value'], entry['id']])
dataset
[0, 8, 1, 9]

Upvotes: 2

Related Questions