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?

1

3 Answers 3

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'}]
Sign up to request clarification or add additional context in comments.

Comments

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}]

Comments

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.