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

Python遍历JSON对象内数组报错:string indices must be integers 求助

问题:遍历JSON对象数组时抛出"string indices must be integers"错误

JSON结构

{"NULSBUSD": {
    "symbol": "NULSBUSD",
    "orderId": 33523092,
    "orderListId": -1,
    "clientOrderId": "54Re4e4iV0bCkIXKyth4Sc",
    "transactTime": 1659875121897,
    "price": "0.00000000",
    "origQty": "187.00000000",
    "executedQty": "187.00000000",
    "cummulativeQuoteQty": "50.10100000",
    "status": "FILLED",
    "timeInForce": "GTC",
    "type": "MARKET",
    "side": "BUY",
    "fills": [
        {
            "price": "0.26790000",
            "qty": "150.00000000",
            "commission": "0.00009529",
            "commissionAsset": "BNB",
            "tradeId": 669893
        },
        {
            "price": "0.26800000",
            "qty": "37.00000000",
            "commission": "0.00002350",
            "commissionAsset": "BNB",
            "tradeId": 669894
        }
    ],
    "delta": 0,
    "tsp": 0.264528
}
}

错误信息

string indices must be integers

原代码

qty = 0.0
for coin in order:
for fill in coin['fills']:
qty += float(fill['qty'])

问题原因

直接for coin in order时,遍历的是字典的键(即字符串"NULSBUSD"),字符串的索引只能是整数,因此coin['fills']会触发错误。

解决方案

方式1:遍历字典的值

直接遍历order中的订单对象:

qty = 0.0
for order_data in order.values():
    for fill in order_data['fills']:
        qty += float(fill['qty'])

方式2:直接通过键获取订单对象

若确定order仅包含"NULSBUSD"一个键,可直接取值:

qty = 0.0
order_data = order['NULSBUSD']
for fill in order_data['fills']:
    qty += float(fill['qty'])

两种方式最终都会计算出总数量187.0。

内容的提问来源于stack exchange,提问作者Pedro Doria Meunier

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:57:10