【问题标题】:Appending JSON file: "TypeError: list indices must be integers or slices, not str"附加 JSON 文件:“TypeError:列表索引必须是整数或切片,而不是 str”
【发布时间】:2018-08-02 20:05:34
【问题描述】:

简而言之,对于数据科学课程,我在 Walmart 上运行一个循环 (Python 3) 来查询商品信息并构建一个以 JSON 格式保存的综合数据集。 (在这种情况下,笔记本电脑属于 walmart api 中的电子产品类别。)

问题: --我可以阅读第一组25个项目 --当我追加时,项目 26 +,创建类型错误

这是我的附加代码

    a = []
    if not os.path.isfile('filename.json'):
        a.append(entry['items'])
        with open('filename.json', mode='w') as f:
            f.write(json.dumps(entry['items'], indent=4))
    else:
        with open('filename.json') as feedsjson:
            feeds = json.load(feedsjson)

        feeds.append(entry['items'])
        with open('filename.json', mode='w') as f:
            f.write(json.dumps(feeds, indent=4))

Here is the json file

这是打印代码。仅适用于项目 1-25

filepath = os.path.join('filename.json')   
with open(filepath) as jsonfile:
    json_data = json.load(jsonfile)

    for i in range(len(json_data)):
        itemId = json_data[i]['itemId']
        print(itemId)

【问题讨论】:

    标签: python json python-3.x walmart-api


    【解决方案1】:

    在您的 json 数据中,您有一个第 26 项的列表。因此,您无法在列表中查找键。

    换句话说,itemId 不是列表的索引。

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多