Python 如何将 MongoDB 查询转换为 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4404742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I turn MongoDB query into a JSON?
提问by TIMEX
for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
In my Django/Python code, I can't return a JSON from a mongo query because of "ObjectID". The error says that "ObjectID" is not serializable.
在我的 Django/Python 代码中,由于“ObjectID”,我无法从 mongo 查询返回 JSON。该错误表示“ObjectID”不可序列化。
What do I have to do? A hacky way would be to loop through:
我需要做什么?一个hacky的方法是循环:
for p in posts:
p['_id'] = ""
采纳答案by Justin Jenkins
The jsonmodule won't work due to things like the ObjectID.
由于 ObjectID 之类的东西,json模块将无法工作。
Luckily PyMongoprovides json_utilwhich ...
幸运的是,PyMongo提供了json_util......
... allow[s] for specialized encoding and decoding of BSON documents into Mongo Extended JSON's Strict mode. This lets you encode / decode BSON documents to JSON even when they use special BSON types.
... 允许 [s] 将 BSON 文档专门编码和解码为 Mongo Extended JSON 的严格模式。这使您可以将 BSON 文档编码/解码为 JSON,即使它们使用特殊的 BSON 类型。
回答by Daniel Roseman
It's pretty easy to write a custom serializer which copes with the ObjectIds. Django already includes one which handles decimals and dates, so you can extend that:
编写一个处理 ObjectIds 的自定义序列化程序非常容易。Django 已经包含一个处理小数和日期的方法,因此您可以扩展它:
from django.core.serializers.json import DjangoJSONEncoder
from bson import objectid
class MongoAwareEncoder(DjangoJSONEncoder):
"""JSON encoder class that adds support for Mongo objectids."""
def default(self, o):
if isinstance(o, objectid.ObjectId):
return str(o)
else:
return super(MongoAwareEncoder, self).default(o)
Now you can just tell jsonto use your custom serializer:
现在您可以告诉json使用您的自定义序列化程序:
thejson = json.dumps({'results':posts}, cls=MongoAwareEncoder)
回答by kelsmj
Here is a simple sample, using pymongo 2.2.1
这是一个简单的示例,使用 pymongo 2.2.1
import os
import sys
import json
import pymongo
from bson import BSON
from bson import json_util
if __name__ == '__main__':
try:
connection = pymongo.Connection('mongodb://localhost:27017')
database = connection['mongotest']
except:
print('Error: Unable to Connect')
connection = None
if connection is not None:
database["test"].insert({'name': 'foo'})
doc = database["test"].find_one({'name': 'foo'})
return json.dumps(doc, sort_keys=True, indent=4, default=json_util.default)
回答by syberkitten
Something even simpler which works for me on Python 3.6 using motor==1.1 pymongo==3.4.0
使用 motor==1.1 pymongo==3.4.0 在 Python 3.6 上对我有用的更简单的东西
from bson.json_util import dumps, loads
for mongo_doc in await cursor.to_list(length=10):
# mongo_doc is a <class 'dict'> returned from the async mongo driver, in this acse motor / pymongo.
# result of executing a simple find() query.
json_string = dumps(mongo_doc)
# serialize the <class 'dict'> into a <class 'str'>
back_to_dict = loads(json_string)
# to unserialize, thus return the string back to a <class 'dict'> with the original 'ObjectID' type.

