pickle
>>>import pickle
>>>d = dict(name='Bob', age=20, score=88)
>>>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)
>>>f.close()
>>>f = open('dump.txt', 'rb')
>>>d = pickle.load(f)
>>>f.close()
>>>d
{'name': 'Bob', 'age': 20, 'score': 88}
JSON
>>>import json
>>>d = dict(name='Bob', age=20, score=88)
>>>json.dumps(d)
{"name": "Bob", "age": 20, "score": 88}
>>>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)方法
print(json.dumps(s, default=lambda obj: obj.__dict__))
>>>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>
obj = dict(name='小明', age=20)
s = json.dumps(obj, ensure_ascii=True)