Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON Dictionary to JSON Array in python

I have JSON dictionary something like this:

{'foo': 3, 'bar': 1}

and i want it in JSON array form:

[ { "key": "foo", "value": 3 }, { "key": "bar", "value": 1 }] 

What should I do?

like image 806
meh Avatar asked Nov 16 '18 15:11

meh


1 Answers

You need to iterate over keys and values for this dictionary and then assign the necessary keys in the new dictionary.

import json

input_dict = {'foo': 3, 'bar': 1}
result = []

for k, v in input_dict.items():
    result.append({'key': k, 'value': v})

print(json.dumps(result))

And the result:

[{'value': 3, 'key': 'foo'}, {'value': 1, 'key': 'bar'}]
like image 90
m0nhawk Avatar answered Sep 30 '22 08:09

m0nhawk