Python requests - quickly know if response is json parsable
Depending on the consistency of the response, you could check if the returned headers include content-type application/json:
resp.headers.get('content-type') == 'application/json'
You can check if the content-type application/json in the response headers:
'application/json' in response.headers.get('Content-Type')
If using Session and not directly requests.(METHOD)
from requests import Sessionfrom simplejson.errors import JSONDecodeErrorclass MySession(Session): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) def request(self, *args, **kwargs): res = super().request(*args, **kwargs) json = res.json def wrapper(): try: return json() except JSONDecodeError: return None res.json = wrapper return res session = MySession()res = session.get("https://api64.ipify.org")if res.json(): print("ok")