0

I am trying to convert a BSON from MongoDB to JSON to using bson.json_util.dumps but this function returns a string rather than a list.

i.e. [{"id":"demo"},{"id":"demo_new"}] --> '[{"id":"demo"},{"id":"demo_new"}]'

Which is difficult to iterate though as it takes the individual element from the string rather than the list.

Is iterating --> '[','{','"',"i","d" and so on Want the iteration to be --> {"id":"demo"} , {"id":"demo_new"}

Any suggestion how to make the string back to a list?

Sankit Acharya
  • 45
  • 2
  • 11
  • 1
    What about the `loads` call? (http://api.mongodb.com/python/current/api/bson/json_util.html#bson.json_util.loads) – Adonis Aug 21 '17 at 09:00
  • Yes, JSON is a textual format, i.e. a string. If you want to turn a BSON document into a list, there's no need to involve JSON at all. – deceze Aug 21 '17 at 09:01
  • @Adonis Thank you, loads did work and converted bson in json to list. but the values are coming with a "u" in front of the keys which is saying its not a valid json . ex {u'_id': ObjectId('59761b2cc6568a4e341b6b89'), u'description': u'lets add some thing new', u'title': u'hi'} any help there ? – Sankit Acharya Aug 21 '17 at 15:12
  • First the `loads` call deserialize a Json formatted string into a python `dict`, so indeed it is no Json anymore. Now the `u` you refer to is to indicate that is a [string encoded in unicode](https://stackoverflow.com/questions/2464959/whats-the-u-prefix-in-a-python-string). I don't understand your issue here to be honest, could you be more explicit? – Adonis Aug 21 '17 at 20:25
  • @Adonis Thanks for your time :). i have explained my problem in good detail in this question any help will be appreciated https://stackoverflow.com/questions/45827542/objects-are-not-valid-as-a-react-child-data-from-mongodb – Sankit Acharya Aug 22 '17 at 21:52

1 Answers1

1

I experienced the same issue.

My solution was the following:

from bson import encode, decode
json = decode(encode(...))

The ... is where you put your query.