码迷,mamicode.com
首页 > 编程语言 > 详细

python 将类对象转换成json

时间:2018-06-17 16:57:10      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:输出   .exe   serial   实例   允许   类对象   字典   dump   参数   

如果将字典转换成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:\Python27\lib\json\encoder.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:\Python27\python.exe E:/python/testspider/fibon.py
{"age": 20, "score": 80, "name": "hello"}

 

python 将类对象转换成json

标签:输出   .exe   serial   实例   允许   类对象   字典   dump   参数   

原文地址:https://www.cnblogs.com/rayong/p/9193003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!