序列化: 通过某种方式把数据结构或对象写入到磁盘文件中或通过网络传到其他节点的过程。
反序列化:把磁盘中对象或者把网络节点中传输的数据恢复为python的数据对象的过程。
序列化最重要的就是json序列化。
JSON(Javascript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAscript (w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
注意:Json仅支持双引号 ,不支持单引号
json的序列化和反序列化import json num = 100 n = json.dumps(num) print(n,type(n)) #100应用之磁盘读写b = True ret = json.dumps(b) print(ret,type(ret)) #true dict = {'age ':12} ret = json.dumps(dict) print(ret,type(ret)) #{"age": 12} li = [1,2,4,3,6] ret = json.dumps(li) print(ret,type(ret)) #[1, 2, 4, 3, 6]
import json
dict = {'age ':12}
ret = json.dumps(dict)
print(ret,type(ret))
#{"age": 12}
with open('a.txt','w',encoding='utf8') as f:
f.write(ret)
with open('a.txt','r',encoding='utf8') as f:
date = f.read()
print(repr(date)) #repr()方法返回对象的字符串形式
dict1 = json.loads(date)
print(dict1,type(dict1))
应用之网络传输
import json
# 反序列化
data = '{"user":"yuan","pwd":123}'
data_dict = json.loads(data)
print(type(data_dict))
# 序列化
res = {'name':'yuan','age':23,'is_married':0}
res_json = json.dumps(res) # 序列化,将python的字典转换为json格式的字符串
print(repr(res_json)) # '{"name": "yuan", "age": 23, "is_married": 0}'



