zoukankan      html  css  js  c++  java
  • python 将类对象转换成json

    如果将字典转换成json,想必都很熟悉了,如果在进阶点,将class类转换成json对象该如何操作了?

    1,先定义一个类

    #定义一个Student类
    class Student(object):
        def __init__(self,name,age,score):
            self.name = name
            self.age = age
            self.score = score

    2,在实例化Student类,传入3个参数

    #实例化这个对象
    s = Student('hello',20,80)

    3,利用json转换s实例化对象,看看是否成功

    print(json.dumps(s))

    4,输出:直接报出TypeError类型错误,不允许直接将类转换成json

      File "C:Python27libjsonencoder.py", line 184, in default
        raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: <__main__.Student object at 0x00000000031239B0> is not JSON serializable
    
    Process finished with exit code 1

    解决方案:

    1,定义一个转换函数

    #定义一个转换函数,将Student类换成json可以接受的类型
    def student2dict(std):
        return {
            'name':std.name,
            'age':std.age,
            'score':std.score
        }

    2,在用json打印出来

    #这样就可以将类对象转换成json了,这里利用json的default属性来调用student2dict函数
    print(json.dumps(s,default=student2dict))

    3,查看输出,这样就能正确的将类对象通过json传输了

    C:Python27python.exe E:/python/testspider/fibon.py
    {"age": 20, "score": 80, "name": "hello"}
  • 相关阅读:
    iOS数据持久化—FMDB框架的简单介绍
    iOS数据持久化—SQLite常用的函数
    多段图动态规划dp
    Cucumber测试驱动开发
    敏捷开发XP
    Android 小票打印USB
    TextInputLayout 用法
    Snackbar 提醒
    PermissionDispatcher 运行时权限框架
    Tinker 热修复
  • 原文地址:https://www.cnblogs.com/rayong/p/9193003.html
Copyright © 2011-2022 走看看