获取类型错误:迭代多级JSON对象时,“NoneType”对象不可迭代

xvw2m8pv  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(170)

我有以下JSON获取响应:

{
"id": "mov_BO381oEATXonG6bj",
"object": "movement",
"amount": 59400,
"post_date": "2020-04-17T00:00:00.000Z",
"description": "Traspaso de:Fintoc SpA",
"transaction_date": "2020-04-16T11:31:12.000Z",
"currency": "CLP",
"reference_id": "123740123",
"type": "transfer",
"pending": false,
"recipient_account": null,
"sender_account": {
    "holder_id": "771806538",
    "holder_name": "Comercial y Producción SpA",
    "number": "1530108000",
    "institution": {
      "id": "cl_banco_de_chile",
      "name": "Banco de Chile",
      "country": "cl"
    }
},
"comment": "Pago factura 198"

},
 {
    "id": "mov_4Ag8xaHXzvq3ea2b",
    "description": "0257478262 Transf.",
    "amount": 450000,
    "currency": "CLP",
    "post_date": "2022-12-01T00:00:00Z",
    "transaction_date": null,
    "type": "transfer",
    "recipient_account": null,
    "sender_account": {
        "holder_id": "257478262",
        "number": null,
        "institution": null,
        "holder_name": "Maria Marco"
    },
    "comment": null,
    "reference_id": "003922335",
    "pending": false,
    "object": "movement"
}

我有下面的python脚本来迭代对象并classify事务,但是当我迭代到内部事务项时,我得到了下面的错误。外部事务项没有给予错误,但是当我想迭代内部项时,我得到了这个错误:

Traceback (most recent call last):
File "/Users/berra/Python/movements.py", line 59, in <module>
for inner_transaction in outer_transaction['sender_account']:
TypeError: 'NoneType' object is not iterable

代码如下所示:

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)

# Parse the JSON data
transactions = json.loads(response.text)

expenses = []
incomes = []

#print(response.text)
for outer_transaction in transactions:
    # if movimiento['sender_account'] is None:
    #     expenses.append(movimiento)

    if outer_transaction['description'] == 'Traspaso de:Fintoc SpA':
        incomes.append(outer_transaction)
   
    if 'sender_account' in outer_transaction:
        #for inner_transaction in outer_transaction:
        for inner_transaction in outer_transaction['sender_account']:
            if inner_transaction['holder_name']=='Maria Marco':
               incomes.append(outer_transaction)
    
print("Expenses:", expenses)
print("Incomes:", incomes)

我正在使用的API文档可从以下位置获得:https://docs.fintoc.com/reference/movements-list
我已经尝试了很多方法来解决这个问题,但是我没能做到。有人知道我错过了什么或者做错了什么吗?提前谢谢你。

nsc4cvqm

nsc4cvqm1#

inner_transaction()不是可迭代的,要访问inner_transaction中的值,只需使用 key,例如outer_transaction['sender_account']['holder_id']

相关问题