数据序列化

../_images/33467946364_3e59bd376a_k_d.jpg

什么是数据序列化?

数据序列化是将结构化数据转换为允许以允许恢复其原始结构的形式共享或存储数据的格式的过程。在某些情况下,数据序列化的第二个目的是最小化数据的大小,从而减少磁盘空间或带宽需求。

平面数据与嵌套数据

在开始序列化数据之前,重要的是确定或决定在数据序列化期间应该如何构造数据-平面或嵌套。下面的示例显示了这两种样式的差异。

平面样式:

{ "Type" : "A", "field1": "value1", "field2": "value2", "field3": "value3" }

嵌套样式:

{"A"
    { "field1": "value1", "field2": "value2", "field3": "value3" } }

有关这两种样式的更多信息,请参阅 Python mailing listIETF mailing listin stackexchange .

序列化文本

简单文件(平面数据)

如果要序列化的数据位于文件中并且包含平面数据,那么Python提供了两种方法来序列化数据。

repr

Python中的repr方法接受单个对象参数,并返回输入的可打印表示:

# input as flat text
a =  { "Type" : "A", "field1": "value1", "field2": "value2", "field3": "value3" }

# the same input can also be read from a file
a = open('/tmp/file.py', 'r')

# returns a printable representation of the input;
# the output can be written to a file as well
print(repr(a))

# write content to files using repr
with open('/tmp/file.py') as f:f.write(repr(a))

ast.literal_eval

literal_eval方法安全地分析和计算python数据类型的表达式。支持的数据类型包括:字符串、数字、元组、列表、dict、booleans和none。

with open('/tmp/file.py', 'r') as f: inp = ast.literal_eval(f.read())

CSV文件(平面数据)

Python中的csv模块实现了以 CSV格式读取和写入表格数据的类。

阅读的简单示例:

# Reading CSV content from a file
import csv
with open('/tmp/file.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

书写的简单示例:

# Writing CSV content to a file
import csv
with open('/temp/file.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(iterable)

可以找到模块的内容、功能和示例 in the Python documentation .

YAML (嵌套数据)

在Python中有许多第三方模块可以解析和读/写YAML文件结构。下面就是这样一个例子。

# Reading YAML content from a file using the load method
import yaml
with open('/tmp/file.yaml', 'r', newline='') as f:
    try:
        print(yaml.load(f))
    except yaml.YAMLError as ymlexcp:
        print(ymlexcp)

可以找到有关第三方模块的文档 在PyYAML文档中

JSON文件(嵌套数据)

Python的JSON模块可以用来读写JSON文件。下面是示例代码。

阅读:

# Reading JSON content from a file
import json
with open('/tmp/file.json', 'r') as f:
    data = json.load(f)

写作:

# Writing JSON content to a file using the dump method
import json
with open('/tmp/file.json', 'w') as f:
    json.dump(data, f, sort_keys=True)

XML(嵌套数据)

可以使用 xml 包裹。

例子:

# reading XML content from a file
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

有关使用的更多文档 xml.dom and xml.sax packages can be found in the Python XML library documentation .

二元的

NumPy数组(平面数据)

Python的NumPy数组可用于对字节表示形式之间的数据进行序列化和反序列化。

例子:

import NumPy as np

# Converting NumPy array to byte format
byte_output = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]).tobytes()

# Converting byte format back to NumPy array
array_format = np.frombuffer(byte_output)

Pickle(嵌套数据)

调用python的本机数据序列化模块 Pickle

下面是一个例子:

import pickle

#Here's an example dict
grades = { 'Alice': 89, 'Bob': 72, 'Charles': 87 }

#Use dumps to convert the object to a serialized string
serial_grades = pickle.dumps( grades )

#Use loads to de-serialize an object
received_grades = pickle.loads( serial_grades )

原生动物

如果你正在寻找一个支持多种语言的序列化模块,谷歌的 Protobuf 类库是一个选项。