5

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?

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
meh
  • 253
  • 2
  • 9
  • 15
  • 1
    what did you do so fat? in any case just create an array, append the items and when you finished based on the use you can jsonify() or json.dumps(): https://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify – Carlo 1585 Nov 16 '18 at 15:40

3 Answers3

7

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'}]
m0nhawk
  • 22,980
  • 9
  • 45
  • 73
4

This could be handled with a list comprehension:

import json
json_dict = {'foo': 3, 'bar': 1}
json_array = [ {'key' : k, 'value' : json_dict[k]} for k in json_dict]
print(json.dumps(json_array))

output:

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

GreenMatt
  • 18,244
  • 7
  • 53
  • 79
1

Try this (Python 2.7 and above):

json_dict = {'foo': 3, 'bar': 1}  # your original dictionary;
json_array = []  # an array to store key-value pairs;

# Loop through the keys and values of the original dictionary:
for key, value in json_dict.items():
    # Append a new dictionaty separating keys and values from the original dictionary to the array:
    json_array.append({'key': key, 'value': value})

One-liner that does the same thing:

json_array = [{'key': key, 'value': value} for key, value in {'foo': 3, 'bar': 1}.items()]

Hope this helps!

Viktor Petrov
  • 444
  • 4
  • 13