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
24.6k9 gold badges50 silver badges74 bronze badges
-
1what 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(): stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonifyCarlo 1585– Carlo 15852018年11月16日 15:40:04 +00:00Commented Nov 16, 2018 at 15:40
3 Answers 3
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'}]
answered Nov 16, 2018 at 15:39
m0nhawk
24.6k9 gold badges50 silver badges74 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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}]
answered Nov 16, 2018 at 15:43
GreenMatt
18.6k9 gold badges56 silver badges82 bronze badges
Comments
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!
answered Nov 16, 2018 at 15:44
Viktor Petrov
4444 silver badges15 bronze badges
Comments
lang-py