Python3 序列化功能代码:
import io
import sys
import json # json
import pickle # pickle
sys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8')
# Python3 序列化之JSON
# Python对象编码成 json 字符串
d={'小明':{'sex':'男','addr':'上海','age':26},'小红':{ 'sex':'女','addr':'上海', 'age':24},}
print(json.dumps(d,ensure_ascii=False,indent=4))
# Python对象编码成 json 字符串,并且写入指定文件中
# d={'小明':{'sex':'男','addr':'上海','age':26},'小红':{ 'sex':'女','addr':'上海', 'age':24},}
# #打开一个名字为‘users.json’的空文件
# fw =open('users.json','w',encoding='utf-8')
# json.dump(d,fw,ensure_ascii=False,indent=4)
#将 json 字符串转换成 Python 的数据类型
d='''{"sex":"男","addr":"上海","age":26}'''
print(json.loads(d))
#打开文件并且将 json 字符串转换成 Python 的数据类型
f =open('users.json','r',encoding='utf-8')
print(json.load(f))
# pickle之dumps()函数
data = ['A', 'B', 'C','D']
datastr = pickle.dumps(data)
print(datastr)
# pickle之dump()函数
with open('test.txt', 'wb') as f:
pickle.dump(data, f)
print('写入成功')
# pickle之loads()函数
msg = pickle.loads(datastr)
print(msg)
# pickle之loads()函数
with open('test.txt', 'rb') as f:
data = pickle.load(f)
print(data)