Han-Gang / test

test
0 stars 0 forks source link

python3运行报错:TypeError: Object of type 'type' is not JSON serializable解决方法 #14

Open Han-Gang opened 5 years ago

Han-Gang commented 5 years ago

我们自定义一个类试试

class User(object):
   def __init__(self, name):
        self.name = name

class UserEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, User):
            return obj.name
        return json.JSONEncoder.default(self, obj)

json_2 = {'user':User('orangle')}
print json.dumps(json_2, cls=UserEncoder)

''' PS D:\code\python\python_abc> python .\json_extention.py {"date": "2014-03-16 14:01:46.738000", "num": 1112} {"user": "orangle"}


作者:orangleliu 来源:CSDN 原文:https://blog.csdn.net/orangleliu/article/details/21324459 版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/dou_being/article/details/82290588