Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create JSON with multiple dictionaries, Python

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
    }
]
like image 254
Vor Avatar asked Dec 21 '22 16:12

Vor


2 Answers

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)
like image 108
Martijn Pieters Avatar answered Jan 06 '23 23:01

Martijn Pieters


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
    }
]
like image 36
jterrace Avatar answered Jan 06 '23 21:01

jterrace