python 如何将MongoDB查询转换为JSON?

z4bn682m  于 2023-08-02  发布在  Python
关注(0)|答案(4)|浏览(222)
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”不可序列化。
我该怎么做?一个简单的方法是循环:

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

vmjh9lq9

vmjh9lq91#

json模块由于ObjectID等原因无法工作。

幸运的是PyMongo提供了json_util...
.允许将BSON文档专门编码和解码为Mongo扩展JSON的严格模式。这允许您将BSON文档编码/解码为JSON,即使它们使用特殊的BSON类型。

jrcvhitl

jrcvhitl2#

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

字符串

wnvonmuf

wnvonmuf3#

编写一个处理ObjectId的自定义序列化程序非常容易。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)

2vuwiymt

2vuwiymt4#

在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.

字符串

相关问题