@@ -1444,8 +1444,8 @@ def json(self, **kwargs: typing.Any) -> typing.Any:
1444
1444
contain valid json or if content-type is not about json.
1445
1445
"""
1446
1446
1447
- if not self .content or "json" not in self . headers . get ( "content-type" , "" ). lower () :
1448
- raise RequestsJSONDecodeError ("response content is not JSON" , self . text or "" , 0 )
1447
+ if not self .content :
1448
+ raise RequestsJSONDecodeError ("response content is not JSON" , "" , 0 )
1449
1449
1450
1450
if not self .encoding :
1451
1451
# No encoding set. JSON RFC 4627 section 3 states we should expect
@@ -1467,10 +1467,13 @@ def json(self, **kwargs: typing.Any) -> typing.Any:
1467
1467
).best ()
1468
1468
1469
1469
if encoding_guess is not None :
1470
+ self .encoding = encoding_guess .encoding
1470
1471
try :
1471
1472
return _json .loads (str (encoding_guess ), ** kwargs )
1472
1473
except _json .JSONDecodeError as e :
1473
1474
raise RequestsJSONDecodeError (e .msg , e .doc , e .pos )
1475
+ else :
1476
+ self .encoding = "utf-8" # try Unicode anyway[...]
1474
1477
1475
1478
plain_content = self .text
1476
1479
@@ -1813,8 +1816,8 @@ async def text(self) -> str | None: # type: ignore[override]
1813
1816
async def json (self , ** kwargs : typing .Any ) -> typing .Any : # type: ignore[override]
1814
1817
content = await self .content
1815
1818
1816
- if not content or "json" not in self . headers . get ( "content-type" , "" ). lower () :
1817
- raise RequestsJSONDecodeError ("response content is not JSON" , await self . text or "" , 0 )
1819
+ if not content :
1820
+ raise RequestsJSONDecodeError ("response content is not JSON" , "" , 0 )
1818
1821
1819
1822
if not self .encoding :
1820
1823
# No encoding set. JSON RFC 4627 section 3 states we should expect
@@ -1836,15 +1839,18 @@ async def json(self, **kwargs: typing.Any) -> typing.Any: # type: ignore[overri
1836
1839
).best ()
1837
1840
1838
1841
if encoding_guess is not None :
1842
+ self .encoding = encoding_guess .encoding
1839
1843
try :
1840
1844
return _json .loads (str (encoding_guess ), ** kwargs )
1841
1845
except _json .JSONDecodeError as e :
1842
1846
raise RequestsJSONDecodeError (e .msg , e .doc , e .pos )
1847
+ else :
1848
+ self .encoding = "utf-8"
1843
1849
1844
1850
plain_content = await self .text
1845
1851
1846
1852
if plain_content is None :
1847
- raise RequestsJSONDecodeError ("response cannot lead to decodable JSON" , "" , 0 )
1853
+ raise RequestsJSONDecodeError ("response cannot lead to unserializable JSON" , "" , 0 )
1848
1854
1849
1855
try :
1850
1856
return _json .loads (plain_content , ** kwargs )
0 commit comments