美文网首页
python json与对象转换

python json与对象转换

作者: proud2008 | 来源:发表于2020-05-22 10:37 被阅读0次
    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'>
    

    相关文章

      网友评论

          本文标题:python json与对象转换

          本文链接:https://www.haomeiwen.com/subject/unafahtx.html