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

如何在AWS IoT Core pubsub.py中提取消息字段值并解决类型错误?

问题解决:提取AWS IoT消息中的color值并避免类型错误

问题原因

你遇到的TypeError: string indices must be integers,是因为某次解析JSON后得到的结果不是预期的字典,而是字符串——此时用['message']这种字符串索引去访问自然会报错。这种情况可能是偶尔收到了格式不符合预期的消息,或是payload的类型处理逻辑存在不一致。

修复方案

在解析消息后增加类型校验和异常捕获,确保只在消息格式正确时提取message字段。修改后的on_message_received函数如下:

import json

# Callback when the subscribed topic receives a message 
def on_message_received(topic, payload, dup, qos, retain, **kwargs):
    print("Received message from topic '{}': {}".format(topic, payload))
    global received_count
    received_count += 1
    if received_count == cmdUtils.get_command("count"):
        received_all_event.set()
    
    try:
        # 直接解析payload(Python 3.6+支持直接解析bytes类型的JSON)
        message_data = json.loads(payload)
        # 校验解析结果是字典且包含message字段
        if isinstance(message_data, dict) and 'message' in message_data:
            color = message_data['message']
            print(color)
        else:
            print("消息格式不符合预期:", message_data)
    except json.JSONDecodeError:
        print("无法解析JSON格式的消息")
    except Exception as e:
        print("处理消息时出错:", str(e))

关键说明

  1. 无需手动decode:Python 3.6及以上版本的json.loads()可以直接处理bytes类型的payload,省去手动解码的步骤,避免类型不一致问题。
  2. 类型校验:通过isinstance(message_data, dict)确保解析结果是字典,再检查'message'字段是否存在,避免非预期格式的消息触发报错。
  3. 异常捕获:捕获JSON解析失败和其他未知异常,保证程序不会因单条异常消息崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:12:30