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
Try
json.dumps(heartbeatData.__dict__)
Are you familiar with dataclasses? It can save some boilerplate code in the constructor, and it easily serializes the data to json:
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?