序列化
- 把变量从内存中变成可存储或者传输的过程称之为序列化,pickling
- 可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上
- 把变量内容从序列化的对象重新读到内存里称之为反序列化,unpickling
- pickle模块来实现序列化
- pickle.dumps():把任意对象序列化成一个bytes,然后,可以把这个bytes写入文件
- pickle.dump():直接把对象序列化后写入一个file-like Object
# 把一个对象序列化并且写入文件import pickled = dict(name='yj', age=24, score=100)# pickle.dumps(d)f = open('dump.txt', 'wb')pickle.dump(d, f)f.close()# 把对象从磁盘读到内存import picklef = open('dump.txt', 'rb')d = pickle.load(f)f.close()print d # 此时的变量和原来的变量是完全不相干的对象,只是内容相同而已# {'age': 24, 'score': 100, 'name': 'yj'}
1.JSON
- JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输
- JSON是标准格式,并且比XML快,而且可以直接在Web页面中读取
(1)JSON和Python内置的数据类型对应
- JSON—————— Python
- {} —————— dict
- [] —————— list
- "string" —————— str
- 1234.56 —————— int或float
- true/false —————— True/False
- null —————— None
(2)Python内置的json模块提供Python对象到JSON格式的转换
- dumps()返回一个str
- dump()直接把JSON写入一个file-like Object
# 把Python对象变成一个JSONimport jsond = dict(name='yj', age=24, score=100)print json.dumps(d)
- loads()把JSON的字符串反序列化
- load()从file-like Object中读取字符串并反序列化
把JSON反序列化为Python对象
import jsonjson_str = '{"name": "yj", "age": 24, "score": 100}'json.loads(json_str)
2.JSON进阶
- dict对象可以直接序列化为JSON的{}
- 用class表示对象
# 将class对象转换为jsonimport jsonclass Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = scores = Student('yj', 24, 100) # Student对象不是一个可序列化为JSON的对象def studentDict(std): return { 'name': std.name, 'age': std.age, 'score': std.score }# Student实例首先被studentDict()函数转换成dict,然后再被顺利序列化为JSONprint json.dumps(s, default=studentDict)# 将json对象转换为class对象def dictStudent(d): return Student(d['name'], d['age'], d['score'])json_str = '{"name": "yj", "age": 24, "score": 100}'print json_loads(json_str, object_hook=dictStudent) # 反序列化的Student实例对象