【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()




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM