python json与对象转换

2020-05-22  本文已影响0人  proud2008
import json


class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def __str__(self):
        str_ = (self.name, self.age, self.score)
        return str(str_)


s = Student('Bob', 20, 88)
#print(json.dumps(s)) #error
jsonStr = json.dumps(s, default=lambda x: x.__dict__)
print(jsonStr)
s1 = json.loads(jsonStr)
print(s1, type(s1))

s2 = json.loads(jsonStr, object_hook=lambda x: Student(x["name"], x["age"], x["score"]))
print(s2, type(s2))

{"name": "Bob", "age": 20, "score": 88}
{'name': 'Bob', 'age': 20, 'score': 88} <class 'dict'>
('Bob', 20, 88) <class '__main__.Student'>
上一篇 下一篇

猜你喜欢

热点阅读