requests标头在json序列化时报错TypeError: Object of type CaseInsensitiveDict is not JSON serializable

发布时间 2023-05-10 11:09:25作者: 测不准

requests的作者似乎为了解决header里大小写兼容的问题,而创建了大小写不敏感的数据结构CaseInsensitiveDict,具体分析可以参见:详解Requests中的数据结构CaseInsensitiveDict

requests返回的response_header即是一个CaseInsensitiveDict类型,而且我们知道response_header里通常并非只有key-value形式的简单数据,而存在更复杂的数据结构,如key:dict、key:list形式等多层嵌套数据。

此时想将response_header序列化,就会出现报错TypeError: Object of type CaseInsensitiveDict is not JSON serializable。

因为CaseInsensitiveDict是requests作者自定义类型,json.dupms并不支持。

为了解决这个问题,可以提前将CaseInsensitiveDict类型的object转为dict再json.dupms序列化,如下:

response_header = json.loads(json.dumps(dict(response.headers)))
request_header = json.loads(json.dumps(dict(response.request.headers)))