Trying to load JSON objects in Python might result into:
TypeError: CaseInsensitiveDict is not JSON serializable
For example reading response headers in Python:
from IPython.display import JSON
JSON(response.headers)
To solve this error you need to:
- use
dict
method - them
json.dumps()
- finally
json.loads()
now the error will disappear:
from IPython.display import JSON
import json
r = response.headers
JSON(json.loads(json.dumps(dict(r))))
Example
The code below will fail with error - TypeError: CaseInsensitiveDict is not JSON serializable
:
import requests
import json
r = requests.get("https://en.wikipedia.org/wiki/Main_Page")
headers_json = json.dumps(r.headers)
While the one below would work: