Sandeep Shyam Sandeep Shyam - 6 months ago 37
JSON Question

python create multiple json objects

I am trying to build a list in Python as below. I want to call this function multiple times and build a json array, when i try with

json.dumps for p in range (0,10)
it adds extra
[]
for each json object

def buildlist():
objects_list = []
d = collections.OrderedDict()
d['batteryLevel'] = random.randint(0, 100)
d['firmwareVersion'] = "2016-04-16-ENGG"
d['macId'] = MACprettyprint(randomMAC())
d['name'] = "".join([random.choice(string.digits+string.letters) for i in xrange(7)])
d['rssi'] = random.randint(0, 100) * -1
d['status'] = random.choice([OPEN, LOCKED])
objects_list.append(d)
return objects_list

Answer

I'm not exactly sure what your question is. But the function you posted will always return a list containing just a single OrderedDict. Why don't you just return the OrderedDict and build the list outside the function?

def builditem():
   d = collections.OrderedDict()
   d['batteryLevel'] = random.randint(0, 100)      
   ...
   d['status'] = random.choice([OPEN, LOCKED])
   return d

json.dumps([builditem() for n in range(10)])