简体   繁体   中英

Error accessing json object fields after bson document fetched from MongoDB via pymongo and converted to json

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM