无法在python中从MongoDB序列化JSON对象

时间:2015-03-10 11:54:22

标签: python json mongodb pymongo

我的MongoDB中存储了以下JSON:

{
"_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对象:

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()

但是,当我尝试从浏览器访问它时,终端上会显示以下错误:

TypeError: DBRef(u'#/definitions/diskDevice', 1) is not JSON serializable
ERROR:root:500 GET /getspecbyid (::1) 5.53ms

我使用的是MongoDB 2.6版 有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

您得到异常,因为DBRef不是json可序列化的。

有一个bson.json_utils模块,它具有用于处理mongo实体的加载/转储方法。

所以,self.write(response)应该是

from bson import json_util #somewhere

self.write(json_util.dumps(response))