在 python/pymongo 中将 bson 转换为 json

Posted

技术标签:

【中文标题】在 python/pymongo 中将 bson 转换为 json【英文标题】:Convert bson to json in python/pymongo 【发布时间】:2014-11-03 05:56:37 【问题描述】:

我正在尝试将直接从 pymongo 获取的 bson 数据转换为 json 数据。有没有使用 pymongo 或其他东西的 python 直接执行此操作的方法?

如果有帮助,这里是代码:

def email_main(request):
    collection = get_collection("nimbus").fullcontact_email_data
    if request.method == "POST":
        data = collection.save(dict(request.POST.iterlists()))
        response = HttpResponse(data, content_type="application/json")
    elif request.method == "GET":
        getParams = convertQuerydictToDict(request.GET)
        page, itemsPerPage = getPageDataFromDict(getParams)
        getParamsWithNoPageData = createDictWithoutPageData(getParams)
        data = collection.find(getParamsWithNoPageData)[page:page+itemsPerPage+1]
        response = HttpResponse(data, content_type="application/json")
    else:
        response = HttpResponse(status=404)
    return response


def convertQuerydictToDict(queryDict):
    return dict(queryDict.iterlists())


def getPageDataFromDict(myDict):
    if "page" in myDict and "itemsPerPage" in myDict:
        page, itemsPerPage = myDict["page"], myDict['itemsPerPage']
    elif "page" in myDict:
        page, itemsPerPage = myDict["page"], 10
    else:
        page, itemsPerPage = 0, 10
    return page, itemsPerPage

def createDictWithoutPageData(myDict):
    newDict = deepcopy(myDict)
    newDict.pop("page", None)
    newDict.pop("itemsPerPage", None)
    return newDict

基本上数据变量需要转换成正确的 json。必须有一些内置的东西可以做到这一点。

为了清楚起见,这是我将数据放入 python 控制台时得到的结果:

>>> data
<pymongo.cursor.Cursor object at 0x4dd0f50>
>>> data[0]
u'blah': u'go', u'_id': ObjectId('540e3fd8bb6933764d5650b7')

ObjectId 不是 json 规范的一部分...

【问题讨论】:

这段代码的行为与您的预期有何不同?您想要转换为 JSON 的 data 变量的类型究竟是什么?我们是假设collection.save 指的是this PyMongo API call,还是别的什么? 数据作为 pymongo 游标对象返回。当您遍历此对象时,返回的数据为 bson 格式,其中包括与 JSON 不兼容的内容。我只希望该数据变量返回 json 而不是 bson,或者尽可能转换它。 你看过json_util module in PyMongo,它似乎解决了这个问题吗? "提供与 json 之间的显式 BSON 转换" 另外,data 不是 BSON 格式。 BSON 被解析成 python 数据结构。 @wdberkeley,对。从这个代码示例中,data 的类型 what 并不明显。不知道这一点,只能推测如何将其转换为 JSON。 【参考方案1】:

正如上面 cmets 中所讨论的,似乎最好的方法是使用 PyMongo 的 json_util module 来处理将 BSON 转换为 JSON 的血腥细节。

【讨论】:

以上是关于在 python/pymongo 中将 bson 转换为 json的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Haskell 中将数据类型转换为 BSON?

如何在python中将光标列表转换为JSON格式?

Python pymongo 񡡙

pymongo的使用方法

python pymongo python

Python pymongo 򐣓