学习python基础记录的实例:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
import pickle #序列化引入的模块
d = dict(name='Box', age=20, score=89)
pickle.dumps(d)
f = open('temp.txt', 'wb')
pickle.dump(d, f)
f.close()
f = open('temp.txt', 'rb')
d = pickle.load(f)
f.close()
print d
with open('temp.txt', 'rb') as f:
d = pickle.load(f)
print d
"""
#将对象转换成json,如果还有别的实例,那就把对象转成dict
#print(json.dumps(s, default=lambda obj: obj.__dict__))
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Ryan', 23, 100)
def student2dict(std):
return {
'name': std.name,
'age': std.age,
'score': std.score
}
print (json.dumps(s, default=student2dict))
#将json转换成对象
def dict2student(d):
return Student(d['name'], d['age'], d['score'])
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
d = json.loads(json_str, object_hook=dict2student)
print d.name
本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2017/11/21 13:59