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

MicroPython中json.dumps返回对象引用而非JSON字符串问题

问题:MicroPython自定义类实例无法被json.dumps序列化

我不常使用Python,当前在树莓派Pico上使用MicroPython开发。定义了Heartbeat类并创建其实例,期望通过json.dumps()将其序列化为JSON字符串发送至后端,但调用后返回的是对象引用<Heartbeat object at 2001e350>,而非预期的JSON格式内容。

相关代码

Heartbeat类定义

class Heartbeat:
    def __init__(self, batteryVoltage, batteryCurrent, batteryPercentage):
        self.type = 'heartbeat'
        self.batteryVoltage = batteryVoltage
        self.batteryCurrent = batteryCurrent
        self.batteryPercentage = batteryPercentage

调用代码

import json
from Heartbeat import Heartbeat

# 省略变量定义部分
heartbeatData = Heartbeat(bus_voltage, (current/1000), P)
message = json.dumps(heartbeatData)
print(message)

预期输出

{
  "type": "heartbeat",
  "batteryVoltage": 90,
  "batteryCurrent": 0.123,
  "batteryPercentage": 99
}

解决办法

方法1:直接使用实例的__dict__属性

MicroPython中自定义类实例默认会用__dict__存储所有实例属性,直接把这个字典传给json.dumps()即可完成序列化:

message = json.dumps(heartbeatData.__dict__)

方法2:给类添加to_dict方法

在Heartbeat类中新增一个方法,手动返回包含所有需要序列化的属性的字典,这种方式更灵活,方便后续扩展或过滤属性:

class Heartbeat:
    def __init__(self, batteryVoltage, batteryCurrent, batteryPercentage):
        self.type = 'heartbeat'
        self.batteryVoltage = batteryVoltage
        self.batteryCurrent = batteryCurrent
        self.batteryPercentage = batteryPercentage
    
    def to_dict(self):
        return {
            'type': self.type,
            'batteryVoltage': self.batteryVoltage,
            'batteryCurrent': self.batteryCurrent,
            'batteryPercentage': self.batteryPercentage
        }

调用时改为:

message = json.dumps(heartbeatData.to_dict())

方法3:自定义JSON编码器(部分MicroPython版本支持)

如果你的MicroPython版本的json模块支持自定义编码器,可以继承json.JSONEncoder重写default方法:

import json

class HeartbeatEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Heartbeat):
            return obj.__dict__
        # 调用父类处理其他类型
        return super().default(obj)

调用时指定编码器:

message = json.dumps(heartbeatData, cls=HeartbeatEncoder)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:00:06