requests 响应头部在转json时,想格式化输出,结果报错TypeError: Object of type CaseInsensitiveDict is not JSON serializable
示例代码
import requests
import json
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
r = requests.get('http://httpbin.org/get')
print(r.headers)
print(json.dumps(r.headers, indent=4))
运行后报错
{'Date': 'Mon, 25 Sep 2023 11:32:31 GMT', 'Content-Type': 'application/json', 'Content-Length': '307', 'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}
Traceback (most recent call last):
File "D:/demo/untitled1/a0_xue/__init__.py", line 7, in
print(json.dumps(r.headers, indent=4))
File "D:\python3.8\lib\json\__init__.py", line 234, in dumps
return cls(
File "D:\python3.8\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "D:\python3.8\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "D:\python3.8\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type CaseInsensitiveDict is not JSON serializable
虽然r.headers 打印出来看到的是字典类型,其实并不是真正的字典, 它是CaseInsensitiveDict
类型
import requests
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
r = requests.get('http://httpbin.org/get')
print(type(r.headers)) #
所以是没法通过json.dupms() 转成json数据。
知道报错原因解决就很简单了,只需转成 dict 类型即可
import requests
import json
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/
r = requests.get('http://httpbin.org/get')
# 响应头部
response_header = json.dumps(dict(r.headers), indent=4)
print(f'响应头部: {response_header}')
# 请求头部
request_header = json.dumps(dict(r.request.headers), indent=4)
print(f'请求头部: {request_header}')
运行结果
响应头部: {
"Date": "Mon, 25 Sep 2023 11:38:01 GMT",
"Content-Type": "application/json",
"Content-Length": "307",
"Connection": "keep-alive",
"Server": "gunicorn/19.9.0",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true"
}
请求头部: {
"User-Agent": "python-requests/2.28.2",
"Accept-Encoding": "gzip, deflate",
"Accept": "*/*",
"Connection": "keep-alive"
}