6

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!

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
johnny
  • 8,696
  • 6
  • 25
  • 36
  • 1
    Excuse me? You can't work with the docs until the driver has converted it to JSON. ``collection.find({}).toArray(function(err, docs) { console.log(docs); //Display array of JSON objects })`` –  May 03 '12 at 21:24
  • 1
    BSON is the native mongodb format. JSON is what you should be receiving as a native object format. – jdi May 03 '12 at 21:27
  • Are you asking how to convert a JSON object into a string? – jdi May 03 '12 at 21:53
  • 1
    I think what everyone is saying, is that the MongoDB driver returns JSON not BSON. BSON is just the internal format used to store your documents. There shouldn't be any conversion required. – Andrew T Finnell May 03 '12 at 22:00
  • Alright, my bad. I had a closer look at the code and I was returning the collection instead of the result of a "find" query. – johnny May 04 '12 at 09:14
  • 7
    The native MongoDB driver doesn't return JSON but a JS object (or an array, depends on the query). That's pretty different since not all values of this object can be serialized to JSON and deserialized correctly (e.g. ObjectID, Date will be converted to String with no way for the deserializer to know how to construct the original object) – Louis Chatriot Dec 18 '12 at 16:03

1 Answers1

0

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

Community
  • 1
  • 1
Ivo Bosticky
  • 6,338
  • 6
  • 34
  • 35