Python:序列化和json

/ Python / 没有评论 / 421浏览

学习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