【Python】python 中 json、class、str 的相互转换

参考: https://blog.csdn.net/qq_29201493/article/details/85697377

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   garbage_test.py
@Time    :   2019/06/15 08:26:17
@Author  :   California Fruit 
@Desc    :   None
'''


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

def json_2str():
    data_json = {'name':'nick',
            'age':12}
    json_str = json.dumps(data_json)
    print type(json_str), json_str

def str_2json():
    json_str = '{"age": 12, "name": "nick"}'
    json_class = json.loads(json_str)
    print type(json_class), json_class

def class_2jsonStr():
    stu = Student('Bob', 20, 88,["三好学生","优秀团干","最佳辩手"])
    print json.dumps(obj=stu.__dict__,ensure_ascii=False)

def jsonStr_2class():

    def dict2student(d):
        return Student(d['name'], d['age'], d['score'],d['reward'])

    json_str = '{"name": "Bob", "age": 20, "score": 88, "reward": ["三好学生", "优秀团干", "最佳辩手"]}'
    student = json.loads(json_str,object_hook=dict2student)
    print(type(student))
    print(student.name)


if __name__ == "__main__":
    jsonStr_2class()


猜你喜欢

转载自www.cnblogs.com/jzsg/p/11026384.html