【问题标题】:list indices must be integers or slices, not str - adding JSON file to MongoDB列表索引必须是整数或切片,而不是 str - 将 JSON 文件添加到 MongoDB
【发布时间】:2019-11-16 16:07:43
【问题描述】:

我已将一个 CSV 文件转换为 JSON,我目前正在尝试从我的 JSON 文件创建一个 MongoDB。

url = "mongodb://localhost:27017"

client = MongoClient(url)

db = client.york

collection = db.inventory

with open ('Inventory.json') as f:
    datastore = json.loads(f.read())

for data in datastore['inventory']:
    collection.insert_one(data)

错误:

TypeError Traceback(最近一次调用最后一次) 在 35 数据存储 = json.loads(f.read()) 36 ---> 37 用于数据存储['inventory'] 中的数据: 38 集合.insert_one(数据)

TypeError: 列表索引必须是整数或切片,而不是 str

【问题讨论】:

  • 您应该在问题中包含确切的数据存储(只需打印它)以获得更准确的帮助。

标签: python mongodb


【解决方案1】:

你做不到

for data in datastore['inventory']:

正如错误所说:list indices must be integers or slices, not str。您可能希望您的数据存储成为包含 'inventory' 键的字典。

【讨论】:

  • 你能解释一下我会怎么做吗?对python真的很陌生
【解决方案2】:

client = MongoClient("mongodb://localhost:27017")

db = client['york']

collection_client = db['inventory']

打开('Inventory.json')为 f: 数据存储 = json.loads(f.read())

collection_client.insert_many(数据存储)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 2016-05-25
    • 2017-11-19
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多