繁体   English   中英

如何将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”不可序列化。

我需要做什么? 一种hacky方式是循环:

for p in posts:
    p['_id'] = ""

由于像ObjectID之类的东西, json模块将无法工作。

幸运的是PyMongo提供了json_util ......

...允许[s]将BSON文档的专门编码和解码转换为Mongo Extended JSON的严格模式。 这使您可以将BSON文档编码/解码为JSON,即使它们使用特殊的BSON类型也是如此。

这是一个简单的示例,使用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)

编写一个可以处理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)

现在你可以告诉json使用你的自定义序列化器:

thejson = json.dumps({'results':posts}, cls=MongoAwareEncoder)

在Python 3.6上使用motor == 1.1 pymongo == 3.4.0对我有用的东西更简单

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM