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

Python遍历JSON遇'NoneType' object is not subscriptable错误咨询

问题根因

报错是因为遍历coins_bought字典时,没有对值为None(对应JSON里的null)的条目做过滤,直接执行coins_bought[coin]["status"]这类子键访问操作,None类型不支持下标索引,就会抛出TypeError: 'NoneType' object is not subscriptable。
另外你现有代码的else分支存在逻辑错误:价格未触发止盈止损属于正常持仓状态,此时直接把coins_bought[coin]设为None,会主动制造无效的null条目,是问题的诱因之一。

修复方法

推荐从两个层面修复,从根源避免报错:

  • 遍历交易字典前,先清理所有值为None的无效条目,避免残留空值影响后续逻辑
  • 修正错误的空值赋值逻辑,仅在卖出成交后再删除对应交易记录,不要在正常持仓时把记录设为None

可直接运行的修复后代码

import json

def sell_coins():
    last_price = get_price()

    # 第一步:清理所有值为None的无效条目
    # 遍历键的列表副本,避免遍历过程中修改字典结构触发报错
    for coin in list(coins_bought.keys()):
        if coins_bought[coin] is None:
            del coins_bought[coin]
    # 清理后写回文件,避免下次运行读取到残留null
    with open(coins_bought_file_path, "w") as file:
        json.dump(coins_bought, file, indent=4)

    # 第二步:执行正常的止盈止损判断
    for coin in coins_bought:
        if coins_bought[coin]["status"] == "FILLED":
            bought_price = float(coins_bought[coin]["bought_at"])
            TP = bought_price + (bought_price * TAKE_PROFIT) / 100
            SL = bought_price - (bought_price * STOP_LOSS) / 100
            current_price = float(last_price[coin]["lastPrice"])

            if current_price > TP or current_price < SL:
                print(f"止盈/止损触发,卖出 {coins_bought[coin]['volume']} 数量的 {coin}")
                sell_limit = client.futures_create_order(
                    symbol=coin,
                    side="SELL",
                    type="MARKET",
                    quantity=coins_bought[coin]["volume"]
                )
                # 卖出完成后再删除对应交易记录,不要提前设空
                del coins_bought[coin]
                with open(coins_bought_file_path, "w") as file:
                    json.dump(coins_bought, file, indent=4)

    print("无符合买卖条件的币种")

备选方案:遍历时跳过空值

如果不想提前清理条目,也可以在循环最开头加空值判断,直接跳过无效条目:

for coin in coins_bought:
    # 遇到空值直接跳过,不执行后续子键访问
    if coins_bought[coin] is None:
        continue
    # 后续接原有的status判断、止盈止损逻辑即可

关键提醒:不要在未触发卖出条件时把持仓记录设为None,这会丢失正常的持仓数据,还会反复触发空值报错。正确的处理方式是卖出成交后直接删除对应键,比设为None更干净,不会残留无效条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:36:47