序列化是指将"结构化数据"转换成"可存储格式"的过程,逆向转换过程被称为逆序列化。
比如在 Python 中,结构化数据对象 dict 并不能直接存储到文件中:
a = {
"Type": "A",
"field1": "value1",
"field2": "value2",
"field3": "value3",
}
with open('./file.txt', 'w') as f:
f.write(a)
#> TypeError: write() argument must be str, not dict
但是我们可以通过序列化操作,将 dict 对象转换为某种可存储格式。比如可以通过序列化操作将 dict 对象转换为字符串序列,从而实现对 dict 对象的存储:
a = {
"Type": "A",
"field1": "value1",
"field2": "value2",
"field3": "value3",
}
print(repr(a)) # 可将repr()理解为一种序列化方法
#> {'Type': 'A', 'field1': 'value1', 'field2': 'value2', 'field3&