TypeError: Object of type 'CommonWeatherResult' is not JSON serializable
来源:8-2 Django依赖服务的高可用

CircleYua
2019-02-15
在使用小程序调用天气api请求时出错,错误的原因是CommonWeatherResult对象不是一个可序列化为JSON的对象。
在老师视频的时候只改了传回结果的函数方式WeatherAPIProxy.ha_requestcity.get(‘city’), timeout=HA_TIMEOUT),但好像因为CommonWeatherResult是一个类还要处理一下返回的结果,使得将返回的类结果转换为JSON的{}形式
写回答
2回答
-
weixin_慕斯卡4281563
2019-07-26
这个问题我今天遇到了,看完视频后,看第二遍3-1的时候result = juhe.weather(city).to_dict()就要这样调用,要把对象转成字典再return JsonResponse,否则TypeError: Object of type CommonWeatherResult is not JSON serializable
00 -
咚咚呛
2019-02-15
嗯,Python类不支持直接的JSON序列化,可以在类里面添加序列化函数,也可添加转换函数返回可序列化对象。比如:
class JsonDemo: def __init__(self): self.name = 'jsondemo' self.age = 10 def to_dict(self): d = {} d['name'] = self.name d['age'] = self.age return d # 序列化使用 json_str = json.dumps(JsonDemo().to_dict())
00
相似问题