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:\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"}

猜你喜欢

转载自www.cnblogs.com/rayong/p/9193003.html