如何在python中的这段代码中以适当的json格式输出

时间:2015-11-02 09:38:57

标签: python mongodb

正在使用python和mongodb。我试图从表中找到名称,通过匹配他们的电话号码。电话号码在我通过从另一个表中获取号码而创建的列表中。它的工作正常,但我打印输出两次。

phone = ["9585507882","9542158582"]           
datum = []
for i in phone:
    cursor = db.name.find({"phone": i},{"_id": False})
    value = yield cursor.count()
    if value is 0:
        pass
    else:
        result = []
        for document in (yield cursor.to_list(length=100)):
            datum.append(document)
        print(datum)
        self.write(bson.json_util.dumps({"result": datum}))

我的输出是

{"result": [{"phone": "9585507882", "name": "Sanjay"}]}{"result": [{"phone": "9585509882", "name": "Sanjay"}, {"phone": "9542158582", "name": "Joe"}]}

任何人都可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

您在self.write()循环中呼叫for,而您仍在构建datum。将其移到外面,使其仅在收集完所有数据后运行:

for i in phone:
    [...]
    if value == 0:  # don't use "is" for value comparison!
        pass
    else:
        [...]
        for document in (yield cursor.to_list(length=100)):
            datum.append(document)
        [...]
self.write(bson.json_util.dumps({"result": datum}))

此外,而不是

if value == 0:
    pass
else:
    [do_stuff]

做得更好

if value:
    [do_stuff]

另外,result = []的用途是什么?你没有对该清单做任何事情。

答案 1 :(得分:0)

更简单的方法是,

phone = ["9585507882","9542158582"]           
cursor = db.name.find({"phone": {"$in":phone}},{"_id": 0}).limit(100)       #$in will get you all document in phone array
result = list(cursor) #list(cursor) will convert cursor to python list
#you can then do anything you want