遍历JSON的subscriptions元素报错,求提取指定字段构建新字典
问题分析与解决
错误原因
你遇到的list indices must be integers or slices, not str错误,核心源于三个数据结构访问的问题:
- 原始数据是数组:你的JSON最外层是
[],解析后data是列表类型,不能直接用data['client']访问,得先取data[0]拿到唯一的对象元素。 - Options是列表:
Outcome下的Options是数组,你试图用字符串索引Options['subscriptions']访问,列表只能用整数索引(比如Options[0])获取内部元素后,再访问其subscriptions属性。 - 结果容器选错:你用单个字典
new_dict存储结果,但目标是包含多个字典的数组,应该用列表来收集每一个处理后的订阅项。
修正后的代码
# 假设data是解析后的JSON列表数据 processed_result = {"subscriptions": []} # 定位到目标subscriptions列表 target_subs = data[0]['client']['Outcome']['Options'][0]['subscriptions'] # 遍历提取所需字段 for sub_item in target_subs: cleaned_sub = { "totalAmount": {"amount": sub_item['totalAmount']['amount']}, "tax": {"amount": sub_item['tax']['amount']} } processed_result["subscriptions"].append(cleaned_sub) # 输出结果 print(processed_result)
执行结果
运行后会生成你需要的结构:
{ "subscriptions": [ { "totalAmount": {"amount": "450.0"}, "tax": {"amount": "0.0"} }, { "totalAmount": {"amount": "25.0"}, "tax": {"amount": "0.0"} } ] }
扩展处理(如果Options有多个元素)
如果Options数组内可能包含多个对象,可嵌套循环遍历所有订阅项:
processed_result = {"subscriptions": []} # 遍历所有Options元素 for option in data[0]['client']['Outcome']['Options']: for sub_item in option['subscriptions']: cleaned_sub = { "totalAmount": {"amount": sub_item['totalAmount']['amount']}, "tax": {"amount": sub_item['tax']['amount']} } processed_result["subscriptions"].append(cleaned_sub)
内容的提问来源于stack exchange,提问作者Helen Helen
相关产品推荐
相关产品推荐

