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 so that my output looks like this:

 [ { "1": 1, "2": 8 }, { "1": 1, "2": 8 }, { "1": 1, "2": 8 } ] 
+4
source share
2 answers

You will need to create a list, add all the mappings to it before converting to JSON:

 output = [] for something in somethingelse: output.append(dict([(x, x**3) for x in xrange(1, 3)]) json.dumps(output) 
+4
source

Your desired result is invalid JSON. I think what you probably wanted to do is add a few dictionaries to the list, for example:

 >>> 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 } ] 
+4
source

Source: https://habr.com/ru/post/1432337/


All Articles