zoukankan      html  css  js  c++  java
  • 【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()
    
    
    
    
    “年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
  • 相关阅读:
    java中的静态变量与实例变量
    Java中的关键字this
    继承和多类的基础(C++)
    11-1:(42)接雨水
    10-2
    10-1
    9-2
    9-1
    8-2
    8-1
  • 原文地址:https://www.cnblogs.com/jzsg/p/11026384.html
Copyright © 2011-2022 走看看