python中序列化模块json和pickle

json模块:json是第三方包,不是系统内置模块,以字符串序列

常用操作有:

json.dumps() # 将变量序列化,即将功能性字符转化为字符串

例:

>>> import json
>>> name = {"name":"egon","age":18}
>>> res = json.dumps(name)
>>> print(res)
{"name": "egon", "age": 18}
>>> print(res,type(res))
{"name": "egon", "age": 18} <class 'str'>

json.loads() #将字符串反序列化成功能性字符

例:

>>> import json
>>> name = "[1,2,3]"
>>> print(type(name))
<class 'str'>
>>> res = json.loads(name)
>>> print(res,type(res))
[1, 2, 3] <class 'list'>
>>>

json.dump(dump_obj,write_file)   将dump_obj序列化后写入文件write_file

例:

>>> tom = {"tom":{"age":19,"score":89}}
>>> f = open(r"C:UsersDELLPycharmProjectsuntitled1four weekuser.info","w",encoding="utf-8")
>>> json.dump(tom,f) #序列化到文件
>>> f.close()
>>> f = open(r"C:UsersDELLPycharmProjectsuntitled1four weekuser.info","r",encoding="utf-8")
>>> res = f.read()
>>> print(res)
{"tom": {"age": 19, "score": 89}}
>>>

json.load(file) 将file中的内容反序列化返回

>>> f = open(r"C:UsersDELLPycharmProjectsuntitled1four weekuser.info","r",encoding="utf-8")
>>> res = json.load(f)
>>> print(res)
{'tom': {'age': 19, 'score': 89}}
>>> print(type(res)) #查看res类型
<class 'dict'>
>>>

pickle模块:以二进制序列

pickle.dumps(obj) 将对象obj序列化为二进制bytes类型

例:

>>> print(res)
{'tom': {'age': 19, 'score': 89}}
>>> pic_res = pickle.dumps(res)
>>> print(pic_res,type(pic_res))
b'x80x03}qx00Xx03x00x00x00tomqx01}qx02(Xx03x00x00x00ageqx03Kx13Xx05x00x00x00scoreqx04KYus.' <class 'bytes'>
>>>

pickle.loads(b_str) 将二进制字符串反序列化为obj对象

>>> print(pic_res,type(pic_res))
b'x80x03}qx00Xx03x00x00x00tomqx01}qx02(Xx03x00x00x00ageqx03Kx13Xx05x00x00x00scoreqx04KYus.' <class 'bytes'>
>>> res = pickle.loads(pic_res)
>>> print(res,type(res))
{'tom': {'age': 19, 'score': 89}} <class 'dict'>
>>>

pickle.dump(obj,write_file) 将对象obj序列化为二进制后存在文件中

>>> print(res)
{'tom': {'age': 19, 'score': 89}}
>>> f = open(r"C:UsersDELLPycharmProjectsuntitled1four weekuser.info","wb")
>>> pickle.dump(res,f)
>>> f.close()
>>> f = open(r"C:UsersDELLPycharmProjectsuntitled1four weekuser.info","rb")
>>> k = f.read()
>>> print(k,type(k))
b'x80x03}qx00Xx03x00x00x00tomqx01}qx02(Xx03x00x00x00ageqx03Kx13Xx05x00x00x00scoreqx04KYus.' <class 'bytes'>
>>>

pinkle.load(file) 将文件中的二进制反序列化为obj对象

>>> f = open(r"C:UsersDELLPycharmProjectsuntitled1four weekuser.info","rb")
>>> res = pickle.load(f)
>>> print(res,type(res))
{'tom': {'age': 19, 'score': 89}} <class 'dict'>
>>>

总结:json和pickle都是将对象序列化,不同之处是json是将对象序列化为Unicode字符串,而pickle是将对象序列化为二进制字符串,也就是bytes类型

在不同语言中对数据的处理和认识是不同的,但每种语言都有一个共同的认识,那就是字符串,在跨平台跨语言传递数据时,序列化是非常常见的

原文地址:https://www.cnblogs.com/dongxixi/p/10685510.html