對象轉換爲json的經常使用方式:python
import json print(json.dumps(s, default=lambda obj: obj.__dict__))
dumps方法先經過lambda表達式把對象變爲dict,而後把dict變爲json串。json
json轉換爲對象的方式:code
class Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = score 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))
loads方法先把json串變爲dict,而後再把dict變爲student對象。對象