简体   繁体   English

通过pymongo从MongoDB中获取bson文档并将其转换为json后,访问json对象字段时出错

[英]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. 我看过很多关于在pymongo中进行MongoDB查询后从bson文档转换为json的帖子。

In my case, I get a document from Cuckoo analysis results stored in MongoDB. 就我而言,我从存储在MongoDB中的Cuckoo分析结果中获取了一个文档。 I can access and print the specific field in that bson document. 我可以访问并打印该bson文档中的特定字段。 However, after converting it to json using json_util from bson and try to access the same field, I get an error. 但是,使用bson的json_util将其转换为json并尝试访问相同的字段后,出现错误。 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': .....}} {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 追溯(最近一次通话):文件“ C:/Users/itisnobody/PycharmProjects/mongo-cuckoo/mongodb-cuckoo.py”,第42行,在打印中doc_json [“ behavior”] TypeError:字符串索引必须是整数,而不是海峡

bson.json_util.dumps converts your document to a JSON string (dumps is short for "dump string"). bson.json_util.dumps将您的文档转换为JSON 字符串bson.json_util.dumps是“ dump string”的缩写)。

It seems that you're attempting to create a "JSON dict", but your document ( doc ) is exactly that. 似乎您正在尝试创建“ JSON dict”,但是您的文档( doc )正是这样。 My guess is that you can just skip the dumps altogether and work with doc directly. 我的猜测是,您可以完全跳过dumps并直接使用doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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