skip to Main Content

I don’t do python very often but just playing with a raspberry pi pico, so I’m using micropython
I have an instance of an object that I want to serialise as json to send to a backend.

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

I create an instance of this, and then call json.dumps, expecting to receive something along the lines of

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

The code is

import json
from Heartbeat import Heartbeat

...

heartbeatData = Heartbeat(bus_voltage, (current/1000), P)
message = json.dumps(heartbeatData)
print(message)

The print is output as:

<Heartbeat object at 2001e350>

Which is not what I assumed json.dumps(heartbeat) would return, its just printing the reference to the object

See above, a stringified version of the object

2

Answers


  1. Try json.dumps(heartbeatData.__dict__)

    Login or Signup to reply.
  2. Are you familiar with dataclasses? It can save some boilerplate code in the constructor, and it easily serializes the data to json:

    In [1]:  import dataclasses
    
    In [2]: @dataclasses.dataclass
       ...: class Heartbeat:
       ...:
       ...:     batteryVoltage: int
       ...:     batteryCurrent: float
       ...:     batteryPercentage: int
       ...:
    
    In [3]: h = Heartbeat(90, 0.123, 99)
    
    In [4]: import json
    
    In [5]: print(json.dumps(dataclasses.asdict(h)))
    {"batteryVoltage": 90, "batteryCurrent": 0.123, "batteryPercentage": 99}
    

    You can force the use of keywords( with dataclasses.dataclass(kw_only=True) ) so that code users will not mix voltage and percentage (having the same type). Also, do you really need the name of the class as a data member? Do you know about isinstance?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search