How to convert or deserialize byte octets to string in python

195 Views Asked by At

enter image description here

I get a message from rocket mq, it's like the string show in the pic above or the below:

b'\x08\xd2\t\x12\x03Tim\x1a(\x08\x04\x12\x18Test ProtoBuf for Python\x1a\n31.10.2019'

The message from rocket mq also has a similar process show in the pic above, the website can be accessed at https://www.freecodecamp.org/news/googles-protocol-buffers-in-python/

How can I change this kind of byte string into readable string or dict using python

I tried decode using utf-8, but failed

1

There are 1 best solutions below

0
Dorian Turba On BEST ANSWER

Have you tried ParseFromString()?

import todolist_pb2 as TodoList

my_list = TodoList.TodoList()
my_list.ParseFromString(b'\x08\xd2\t\x12\x03Tim\x1a(\x08\x04\x12\x18Test ProtoBuf for Python\x1a\n31.10.2019')

If we follow the tutorial, you should have generated this module and have access to this functions that allows you to serialize and deserialize data.

Each Protocol Buffer class has methods for reading and writing messages using a Protocol Buffer-specific encoding, that encodes messages into binary format. Those two methods are SerializeToString() and ParseFromString().