Problem storing recieved packet as JSON file

ERROR:root:Error while handling message from radio Object of type bytes is not JSON serializable

I am getting this error while trying to store the JSON data of the incoming packet in a JSON file as follows:

def onReceive(packet, interface): # called when a packet arrives
    print(f"Received: {packet}")
    new = open('new.json', "w", encoding='utf-8')
    json.dump(packet, new, indent = 2)

Python byte arrays can’t be directly stored in json. You’ll need to convert them to a somehow (either as utf8 if you know they are characters or usually base64)

The provided packet is a dictionary with a number of entries.

so will the following code work?

Received: {'from': 3294300496, 'to': 4294967295, 'decoded': {'data': {'portnum': 'TEXT_MESSAGE_APP', 'payload': b'hi'}}, 'id': 2707257921, 'rxSnr': 9.75, 'hopLimit': 1, 'fromId': '!240ac45b0950', 'toId': '^all'}
ERROR:root:Error while handling message from radio 'dict' object has no attribute 'decode'
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/meshtastic/", line 676, in __reader
  File "/usr/local/lib/python3.8/dist-packages/meshtastic/", line 384, in _handleFromRadio
  File "/usr/local/lib/python3.8/dist-packages/meshtastic/", line 513, in _handlePacketFromRadio
    pub.sendMessage(topic, packet=asDict, interface=self)
  File "/usr/local/lib/python3.8/dist-packages/pubsub/core/", line 216, in sendMessage
  File "/usr/local/lib/python3.8/dist-packages/pubsub/core/", line 452, in publish
    self.__sendMessage(msgData, topicObj, msgDataSubset)
  File "/usr/local/lib/python3.8/dist-packages/pubsub/core/", line 482, in __sendMessage
    listener(data, self, allData)
  File "/usr/local/lib/python3.8/dist-packages/pubsub/core/", line 237, in __call__
  File "", line 39, in onReceive
    data = packet.decode('utf-8')
AttributeError: 'dict' object has no attribute 'decode'

Now the follwing code is giving the above error

def onReceive(packet, interface):
      print(f"Received: {packet}")
      data = packet.decode('utf-8')
      #packet = base64.b64encode(packet)
      packet = json.dumps(data)
      new = open('new.json', "w")
      json.dump(packet, new, indent = 2)

hmm - I haven’t tried running this code, but perhaps try:

Your code is not converting the entire

{'from': 3294300496, 'to': 4294967295, 'decoded': {'data': {'portnum': 'TEXT_MESSAGE_APP', 'payload': b'now'}}, 'id': 2820000253, 'rxSnr': 8.75, 'hopLimit': 1, 'fromId': '!240ac45b0950', 'toId': '^all'}

to JSON format. it is only converting the payload data. I need the entire above dictionary to be converted.

I think you’ll need to step through it with the python debugger. (Vscode includes a nice one)

It looks like you don’t need “packet = json.dumps(data)”