Anvith
Anvith

Reputation: 507

Unable to serialize JSON object from MongoDB in python

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" : {         
    }
  }
}

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

I am using MongoDB version 2.6 Can someone help me resolve this issue?

Upvotes: 2

Views: 2888

Answers (1)

Tasos Vogiatzoglou
Tasos Vogiatzoglou

Reputation: 2453

You get the exception because DBRef is not json serializable.

There is a bson.json_utils module that has loads/dumps methods for handling mongo entities.

So, the self.write(response) should be

from bson import json_util #somewhere

self.write(json_util.dumps(response))

Upvotes: 4

Related Questions