本文介绍了无法在Python中从MongoDB序列化JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在MongoDB中存储了以下JSON:
I have the following JSON stored in my MongoDB:
{
"_id" : ObjectId("54fed786265e7f01d66ca778"),
"id" : "http://some.site.somewhere/entry-schema#",
"schema" : "http://json-schema.org/draft-04/schema#",
"description" : "schema for an fstab entry",
"type" : "object",
"required" : [
"storage"
],
"properties" : {
"storage" : {
"type" : "object",
"oneOf" : [
DBRef("#/definitions/diskDevice", 1),
DBRef("#/definitions/diskUUID", 2),
DBRef("#/definitions/nfs", 3),
DBRef("#/definitions/tmpfs", 4)
]
}
},
"definitions" : {
"diskDevice" : {
},
"diskUUID" : {
},
"nfs" : {
},
"tmpfs" : {
}
}
}
我使用龙卷风编写了以下python代码,以访问此JSON对象:
I have written the following the python code using tornado to access this JSON object:
import pymongo
from pymongo import Connection
import tornado.escape
import tornado.ioloop
import tornado.web
class MongoTransactions:
def __init__(self):
print('Initializing MongoTransaction class')
def mongoConnect(self, dbName, collectionName):
connection = Connection()
db = connection[dbName]
collection = db[collectionName]
print('connection string is: ' + str(collection))
class GetSpecByIdHandler(tornado.web.RequestHandler):
def set_default(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
def get(self):
connection = Connection()
db = connection['petstores']
collection = db['petstore']
response = collection.find_one({},{"_id" : 0})
self.write(response)
#print response
application = tornado.web.Application([
(r"/getspecbyid", obj.GetSpecByIdHandler)
])
if __name__ == "__main__":
obj = MongoTransactions()
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
但是,当我尝试从浏览器访问它时,在终端上显示以下错误:
However, when I try to access it from the browser, the following error is displayed on the terminal:
TypeError: DBRef(u'#/definitions/diskDevice', 1) is not JSON serializable
ERROR:root:500 GET /getspecbyid (::1) 5.53ms
我正在使用MongoDB 2.6版有人可以帮我解决这个问题吗?
I am using MongoDB version 2.6Can someone help me resolve this issue?
推荐答案
您会收到异常,因为DBRef不能进行json序列化.
You get the exception because DBRef is not json serializable.
有一个bson.json_utils
模块,该模块具有用于处理mongo实体的加载/转储方法.
There is a bson.json_utils
module that has loads/dumps methods for handling mongo entities.
所以self.write(response)
应该是
from bson import json_util #somewhere
self.write(json_util.dumps(response))
这篇关于无法在Python中从MongoDB序列化JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!