You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python遍历包含字典列表的JSON时出现TypeError问题的排查与解决方案请求

Python遍历包含字典列表的JSON时出现TypeError问题的排查与解决方案

看起来你遇到的TypeError: string indices must be integers, not 'str'是因为遍历JSON数据的逻辑出了问题,我来帮你拆解问题并修正代码:

问题根源分析

你的代码里有两个关键错误:

  1. 当你执行for each_items_in_json in respJson:时,respJson是一个字典,默认遍历的是字典的键(比如'cart'、'complete_cart'),而不是键对应的值。
  2. 当你判断each_items_in_json=='cart'后,又执行了for items_in in each_items_in_json:——这里的each_items_in_json是字符串'cart',所以这个循环会遍历字符串的每个字符(比如'c'、'a'、'r'、't'),这时候items_in是单个字符,你再用items_in['benefit_id']自然会报错,因为字符串只能用整数索引。

修正后的代码

下面是调整后的完整代码,我会标注关键修改点:

import json  # 确保导入了json模块(如果还没导入的话)

def userCompleteCart(self):
    response = self.client.get(url=GET_userCart.userCart_EndPoint)    
    respJson = response.json()
    storeListsItemsFromJSON = {}
    JSONtoUseInNextAPI = {}
    
    # 关键修改1:直接获取cart对应的列表,遍历里面的每个字典项
    for cart_item in respJson.get('cart', []):
        # 关键修改2:合并条件判断,用get方法避免KeyError,提升可读性
        if (cart_item.get('benefit_id') != '-1' 
            and cart_item.get('plan_id') != '-1' 
            and cart_item.get('change') == 0 
            and cart_item.get('id') is not None):
            # 注意:如果有多个符合条件的项,这里会覆盖user_id;若要收集多个,建议用列表
            storeListsItemsFromJSON["user_id"] = cart_item['id']
    
    storeListsItemsFromJSON["mid-term"] = False      
    JSONtoUseInNextAPI = json.dumps(storeListsItemsFromJSON)                    
    print(JSONtoUseInNextAPI)

    response = self.client.post(url="api/user/complete-cart", data=JSONtoUseInNextAPI)
    if response.status_code == 200:
        print("\033[92m {}\033[00m".format("[API_CALL]: Success call POST/user-complete-cart API:"), response.status_code)          
    else:
        print("\033[91m {}\033[00m".format("[FAIL_CASE]: Failed call for POST/user-complete-cart API !!"), response.status_code)

关键修改说明

  1. 正确遍历cart列表:用respJson.get('cart', [])直接获取cart对应的列表(get方法可以避免cart键不存在时抛出KeyError,默认返回空列表),然后遍历列表中的每个字典项cart_item。
  2. 安全的条件判断:使用get方法获取字典值,避免因键缺失报错;同时将多层嵌套的if合并为一个条件块,代码更简洁易读。
  3. 移除错误的字符串遍历:删掉了对字符串'cart'的无效遍历,直接操作目标列表中的字典元素。

额外优化建议

如果你的cart里可能有多个符合条件的项,而不是只取最后一个,建议把user_id改成列表来收集所有符合要求的id:

storeListsItemsFromJSON["user_ids"] = []
for cart_item in respJson.get('cart', []):
    if (cart_item.get('benefit_id') != '-1' 
        and cart_item.get('plan_id') != '-1' 
        and cart_item.get('change') == 0 
        and cart_item.get('id') is not None):
        storeListsItemsFromJSON["user_ids"].append(cart_item['id'])

这样可以保留所有符合条件的结果,更灵活适配后续API的需求。

备注:内容来源于stack exchange,提问作者Bonzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 18:54:50