python - 使用 python 创建正确的 JSON 字符串

标签 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 的我的输出截图 enter image description here

最佳答案

如何先将所有内容保存在列表中,然后将该列表转储到 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}))

关于python - 使用 python 创建正确的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31531090/

相关文章:

python - 哪个是更新所有 anaconda python 包的正确命令?

c# - 在多线程 C# 应用程序中嵌入 Python

javascript - 需要在 JSON 格式的 API 输出中搜索值并打印整个数组内容

java - 如何将 Mongodb 聚合(展开、匹配和项目)查询转换为 java 代码

python - 确定检测器系统中旋转正方形的重叠

python - Pandas:通过提供标题名称来读取列

iOS NSDictionary 值确定 bool 值是否来自 JSON bool 值

ruby-on-rails - Rails 3.2,处理损坏的请求体(MultiJson::DecodeError)

node.js - 蒙戈没有数据

node.js - MongoDB 更新子文档更改其_id