DEV Community

Zephaniah Joshua
Zephaniah Joshua

Posted on

Serialisation

Alt Text

Previously we talked about parsing data so it could be sent over a network and we used an example code in python. parsing is a simple form of serialisation.

Serialisation is converting data into a stream of bytes so that it can be stored or transmitted.

Remember our example information that was to be sent over the internet that has two data types an integer and a string

data1 = “hello” #string
data2 = 123  #interger
Enter fullscreen mode Exit fullscreen mode

Now we can use pickle a serialisation module in python(FYI: marshal, JSON are other python serialisation modules ) to convert this data to bytes and send them over the network.
NOTE: any data type can be serialised with pickle

import pickle  

data1 = “hello” #string
data2 = 123  #interger

#creating our message as a tuple
message = (data1, data2)

#converting data to a stream of bytes with pickle
msg = pickle.dumps(message)
print(msg)
Enter fullscreen mode Exit fullscreen mode

When this message is received it needs to be deserialised

import pickle 

#deserialising
message = pickle.loads(msg)


data1 = message[0]
data2 = message[1]

print(data1)
print(data2)
Enter fullscreen mode Exit fullscreen mode

Warning as stated in the pickle documentation deserialisation(unpickling) can be exploited by crafting data to cause arbitrary code execution.

Hope this gives you a basic understanding on serialisation and how to use the pickle python module to do it. Please do leave suggestions or questions in the comment box or contact me @black_strok3

Photo by Neo from Pexels

Top comments (0)