[英]Convert bson to json in python/pymongo
I'm trying to convert bson data gotten straight from pymongo into json data. 我正在尝试将从pymongo直接获得的bson数据转换为json数据。 Is there a straight forward way to do this with python using pymongo or something else?
使用pymongo或其他东西使用python有没有直接的方法呢?
Here's the code if it helps: 这是代码,如果它有帮助:
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
basically that data variable needs to get turned into proper json. 基本上,数据变量需要变成适当的json。 There must be some built in thing that does this.
必须有一些内置的东西来做到这一点。
For clarity here's what I get when I put data into the python console: 为清楚起见,这是我将数据放入python控制台时得到的结果:
>>> data
<pymongo.cursor.Cursor object at 0x4dd0f50>
>>> data[0]
{u'blah': u'go', u'_id': ObjectId('540e3fd8bb6933764d5650b7')}
ObjectId is not part of the json spec... ObjectId不是json规范的一部分......
正如上面的评论中所讨论的,似乎最好的方法是使用PyMongo的json_util
模块来处理将BSON转换为JSON的血腥细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.