MongoDB: BSON to JSON

johnny picture johnny · May 3, 2012 · Viewed 12.9k times · Source

I'm using the native mongoDB driver for node.js. I'd like to get some data from the database and send it as a JSON string via HTTP. Is there a way to convert the BSON to JSON or directly retrieve the data as JSON from the database?

Thanks!

Answer

Ivo Bosticky picture Ivo Bosticky · May 4, 2012

In python you can use the simplejson encoder to convert bson to json as follows:

result = db.mycol.find({ ....})
json = simplejson.dumps(result)

It will convert all simple objects, but will have difficulties with others, for example datetime will not work. To deal with this issue the following may work: MongoDB Object Serialized as JSON