我正在尝试在Python中构建一个列表,如下所示。我想多次调用这个函数并构建一个json数组,当我尝试使用json.dumps for p in range (0,10)
时,它会为每个json对象添加额外的[]
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
答案 0 :(得分:0)
我不确定你的问题是什么。但是您发布的函数将始终返回仅包含单个OrderedDict的列表。为什么不直接返回OrderedDict并在函数外部构建列表?
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)])