从命令行使用Python脚本中的Json文件填充Mongo数据库

时间:2019-02-07 21:16:09

标签: python node.js mongodb express

page = open("npm.json", "r")
parsed = json.loads(page.read())

for i in parsed["dependencies"]:
    collection.insert_one(i)

嗨,我正在尝试读取一个json文件,并用名为ependencies的行填充我的mongoDB。它不断给我带来错误。我尝试插入,insert_one&insert_many无济于事。

以下是我得到的错误

    File "database.py", line 43, in <module>
    collection.insert_one(i)
  File "/usr/local/lib/python3.6/dist-packages/pymongo/collection.py", line 684, in insert_one
    common.validate_is_document_type("document", document)
  File "/usr/local/lib/python3.6/dist-packages/pymongo/common.py", line 453, in validate_is_document_type
    "collections.MutableMapping" % (option,))
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "database.py", line 43, in <module>
    collection.insert_one(i)
  File "/usr/local/lib/python3.6/dist-packages/pymongo/collection.py", line 684, in insert_one
    common.validate_is_document_type("document", document)
  File "/usr/local/lib/python3.6/dist-packages/pymongo/common.py", line 453, in validate_is_document_type
    "collections.MutableMapping" % (option,))
TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

json文件是节点依赖关系的列表。我在节点项目上运行了命令npm list。谁能帮忙谢谢

1 个答案:

答案 0 :(得分:0)

看来您在dependencies中的数据是dictionary。这意味着,当您对其进行迭代时,将获得字符串(在这种情况下,这是键)。

示例如下:

my_entry = {'a': 1, 'b': 2}

for i in myentry:
    print(i)

# will print 'a' then 'b', not 1 then 2

我假设每个依赖项都是一个键,并且您想插入值。所以

# dictionary.values() will give you just the values
for v in parsed['dependencies'].values():
    if isinstance(v, dict):
        collection.insert_one(v)
    else:
        raise ValueError("object is not dictionary")

Mongo仅接受jsonbson条目,就像字典一样。传递keys时,您试图插入string类型的对象,但不支持