序列化 pickle模块 json模块 python

mac2026-01-04  7

pickle # 仅适用python >>>import pickle >>>d = dict(name='Bob', age=20, score=88) # 输入值 dict 字典 # 对象序列化成一个bytes >>>pickle.dumps(d) b'\x80\x04\x95$\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x04name\x94\x8c\ \x03Bob\x94\x8c\x03age\x94K\x14\x8c\x05score\x94KXu.' >>>f = open('dump.txt', 'wb') # 打开文件,以二进制写入 >>>pickle.dump(d, f) # 将d的值写入f中 >>>f.close() # 保存,关闭文件 >>>f = open('dump.txt', 'rb') # 打开文件,以二进制读取 # 从一个file-like Object中直接反序列化出对象 >>>d = pickle.load(f) >>>f.close() # 保存,关闭文件 >>>d # 输出d的值 {'name': 'Bob', 'age': 20, 'score': 88} JSON # 不同的编程语言通用模块,标准格式 >>>import json >>>d = dict(name='Bob', age=20, score=88) # 类似的,dump()方法可以直接把JSON写入一个file-like Object >>>json.dumps(d) # 返回一个str,内容就是标准的JSON {"name": "Bob", "age": 20, "score": 88} # 要把JSON反序列化为Python对象,用loads()或者对应的load()方法, # 前者把JSON的字符串反序列化,后者从file-like Object中读取字符串并反序列化 >>>json_str = '{"age": 20, "score": 88, "name": "Bob"}' >>>json.loads(json_str) {'age': 20, 'score': 88, 'name': 'Bob'} >>>import json >>>class Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = score >>>def student2dict(std): return { 'name' : std.name, 'age' : std.age, 'score' : std.score } >>>s = Student('Bob', 20, 88) >>>print(json.dumps(s,default=student2dict)) {"name": "Bob", "age": 20, "score": 88} 偷懒方法 可不用写student2dict(std)方法 # 为通常class的实例都有一个__dict__属性,它就是一个dict, # 用来存储实例变量。也有少数例外,比如定义了__slots__的class print(json.dumps(s, default=lambda obj: obj.__dict__)) # 把JSON反序列化为一个Student对象实例,loads()方法首先转换出一个dict对象, # 然后我们传入的object_hook函数负责把dict转换为Student实例 >>>def dict2student(d): return Student(d['name'],d['age'],d['score']) >>> json_str = '{"age": 20, "score": 88, "name": "Bob"}' >>> print(json.loads(json_str, object_hook=dict2student)) <__main__.Student object at 0x0000028245E03AF0> # json.dumps()提供了一个ensure_ascii参数 obj = dict(name='小明', age=20) s = json.dumps(obj, ensure_ascii=True) # 为True时 会把中文转成Unicode码 默认 # 为False时 可输出中文
最新回复(0)