I have this code:
>>> import simplejson as json
>>> keys = dict([(x, x**3) for x in xrange(1, 3)])
>>> nums = json.dumps(keys, indent=4)
>>> print nums
{
"1": 1,
"2": 8
}
But I want to create a loop to make my output looks like this:
[
{
"1": 1,
"2": 8
},
{
"1": 1,
"2": 8
},
{
"1": 1,
"2": 8
}
]
You'd need to create a list, append all the mappings to that before conversion to JSON:
output = []
for something in somethingelse:
output.append(dict([(x, x**3) for x in xrange(1, 3)])
json.dumps(output)
Your desired output is not valid JSON. I think what you probably meant to do was to append multiple dictionaries to a list, like this:
>>> import json
>>> multikeys = []
>>> for i in range(3):
... multikeys.append(dict([(x, x**3) for x in xrange(1, 3)]))
...
>>> print json.dumps(multikeys, indent=4)
[
{
"1": 1,
"2": 8
},
{
"1": 1,
"2": 8
},
{
"1": 1,
"2": 8
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With