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

迭代多层JSON对象时遇TypeError: 'NoneType'不可迭代问题求助

Fintoc API交易分类脚本报错排查思路

错误原因分析

报错TypeError: 'NoneType' object is not iterable的核心问题有两个:

  1. 错误将字典对象当数组遍历:sender_account是单个字典结构(比如{"holder_id": "...", "holder_name": "..."}),不是可迭代的数组,直接用for...in遍历会触发逻辑错误;若某条交易的sender_account值为null(对应Python的None),就会直接抛出该异常。
  2. 缺失空值校验:仅判断sender_account字段存在,但未校验其值是否为None,API返回的交易中可能存在sender_account为null的情况。

修复方案

1. 修正遍历逻辑:直接访问字典属性

sender_account是单个对象,无需循环遍历,直接判断其属性即可:

if 'sender_account' in outer_transaction:
    sender_account = outer_transaction['sender_account']
    # 先校验非空,再判断holder_name
    if sender_account is not None and sender_account.get('holder_name') == 'Maria Marco':
        incomes.append(outer_transaction)

2. 完善空值与字段校验

用get()方法访问嵌套属性,避免键不存在的KeyError,同时逐层校验空值:

sender_account = outer_transaction.get('sender_account')
if sender_account is not None:
    if sender_account.get('holder_name') == 'Maria Marco':
        incomes.append(outer_transaction)

完整修正代码

import requests
import json

url = "https://api.fintoc.com/v1/accounts/acc_qNDRKQeTpbAKvpnW/movements?link_token=token"

headers = {
    "accept": "application/json",
    "Authorization": "authorizedKey."
}

response = requests.get(url, headers=headers)
transactions = json.loads(response.text)

expenses = []
incomes = []

for outer_transaction in transactions:
    # 匹配指定描述的收入
    if outer_transaction.get('description') == 'Traspaso de:Fintoc SpA':
        incomes.append(outer_transaction)
    
    # 匹配指定发送方的收入
    sender_account = outer_transaction.get('sender_account')
    if sender_account is not None and sender_account.get('holder_name') == 'Maria Marco':
        incomes.append(outer_transaction)

print("Expenses:", expenses)
print("Incomes:", incomes)

额外排查技巧

  • 打印完整交易结构,确认异常数据:print(json.dumps(transactions, indent=2)),查看是否存在sender_account为null或结构异常的交易
  • 用异常捕获定位问题交易:
for idx, outer_transaction in enumerate(transactions):
    try:
        # 你的分类逻辑
    except Exception as e:
        print(f"第{idx}条交易出错:{e}")
        print(f"交易详情:{json.dumps(outer_transaction, indent=2)}")

内容的提问来源于stack exchange,提问作者Bernardo Troncoso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:05:17