使用python创建适当的JSON字符串

时间:2015-07-21 05:32:52

标签: python json mongodb

嗨,我是python编程的新手。在这里,我使用转储从我的mongodb获取输出。但是我在PostMan中收到格式错误的JSON字符串错误。

我的代码是:

cursor = db.Details.find()
    for document in (yield cursor.to_list(length=100)):
        self.write(bson.json_util.dumps(document))

我的输出是:

{"Name": "Will","_id": {"$oid": "55a8f075a382c32392b75bad"}}
{"Name": "Alex", "_id": {"$oid": "55acc2205d8882ef8a667d34"}}
{"data": null, "status": "success"}

我希望输出如何:

{"data": [
   {"Name": "Will","_id": {"$oid": "55a8f075a382c32392b75bad"}},
   {"Name": "Alex", "_id": {"$oid": "55acc2205d8882ef8a667d34"}}
], "status": "success"}

请帮帮我。

提前致谢

PostMan的My Output屏幕截图 enter image description here

1 个答案:

答案 0 :(得分:2)

如何首先将所有内容保存在列表中,然后将该列表转储到json

data = []
cursor = db.Details.find()
    for document in (yield cursor.to_list(length=100)):
        data.append(document)

self.write(bson.json_util.dumps({"data": data}))    

修改: 要获得所需输出的success变量,可以尝试

data = []
status = ""

cursor = db.Details.find()
    for document in (yield cursor.to_list(length=100)):
        if 'status' in document: # check if key 'status' in document
            status = document[status]
        else:
            data.append(document)

self.write(bson.json_util.dumps({"data": data, "status": status}))