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?
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?
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'}]
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}]
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!