python 将类对象转换成json

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

 

1,先定义一个类json

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

 

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

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

 

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

print(json.dumps(s))

 

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

  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

 

解决方案:code

1,定义一个转换函数对象

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

 

2,在用json打印出来blog

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

 

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

C:\Python27\python.exe E:/python/testspider/fibon.py
{"age": 20, "score": 80, "name": "hello"}
相关文章
相关标签/搜索