Reputation: 15
I have seen many posts about converting to json from bson documents returned after a MongoDB query in pymongo.
In my case, I get a document from Cuckoo analysis results stored in MongoDB. I can access and print the specific field in that bson document. However, after converting it to json using json_util from bson and try to access the same field, I get an error. Is there still things to be done to use the object?
Here is the code:
from pymongo import MongoClient
from bson.json_util import dumps, default
<...pymongo code for connecting to MongoDB server...>
result_cursor = analysis.find({"info.id": 1770}, {"behavior.summary": 1})
for doc in result_cursor:
print doc["behavior"]
doc_json = dumps(doc, default=default)
print doc_json["behavior"]
From the above code, first print works fine, but the last one triggers an exception because i think it sees the object as a list not a dictionary:
{u'summary': {u'files': .....}}
Traceback (most recent call last): File "C:/Users/itisnobody/PycharmProjects/mongo-cuckoo/mongodb-cuckoo.py", line 42, in print doc_json["behavior"] TypeError: string indices must be integers, not str
Upvotes: 0
Views: 923
Reputation: 64298
bson.json_util.dumps
converts your document to a JSON string (dumps is short for "dump string").
It seems that you're attempting to create a "JSON dict", but your document (doc
) is exactly that. My guess is that you can just skip the dumps
altogether and work with doc
directly.
Upvotes: 1