如何将MongoDB查询转换为JSON? [英] How do I turn MongoDB query into a JSON?
问题描述
for p in db.collection.find({"test_set":"abc"}):
posts.append(p)
thejson = json.dumps({'results':posts})
return HttpResponse(thejson, mimetype="application/javascript")
在我的Django/Python代码中,由于"ObjectID",我无法从mongo查询返回JSON.该错误表明"ObjectID"不可序列化.
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.
我该怎么办? 一种骇人听闻的方法是遍历:
What do I have to do? A hacky way would be to loop through:
for p in posts:
p['_id'] = ""
推荐答案
json 模块由于ObjectID之类的原因而无法正常工作.
The json module won't work due to things like the ObjectID.
幸运的是 PyMongo 提供了
Luckily PyMongo provides json_util which ...
... allow [s]用于特殊编码和 将BSON文档解码为Mongo 扩展JSON的严格模式.这让 您将BSON文档编码/解码为 JSON,即使他们使用特殊的BSON 类型.
... 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.
这篇关于如何将MongoDB查询转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!