Search⌘ K
AI Features

Serialization and Deserialization

Explore how to convert Python data types like lists, tuples, and dictionaries into JSON format and back using serialization and deserialization. Understand using Python's json module for writing and reading complex data to and from files or strings.

Compared to strings, reading/writing numbers to and from a file is tedious. This is because the write() function writes a string to a file and the read() function returns a string read from a file. So we need to do conversions while reading/writing, as shown in the following program:

Python 3.8
f = open('numberstxt', 'w+')
f.write(str(233)+'\n')
f.write(str(13.45))
f.seek(0)
a = int(f.readline( ))
b = float(f.readline( ))
print(a + a)
print(b + b)

If we want to read/write more complicated data in the form of tuples, dictionaries, etc., to and from a file using the method ...