Home > Net >  I want to load a random dad joke form this website and but there is an error with json.loads
I want to load a random dad joke form this website and but there is an error with json.loads

Time:06-20

here is the full error message for when i run the code that is under this error message:

PS C:\Users\Admin> & C:/Users/Admin/AppData/Local/Programs/Python/Python39/python.exe c:/Users/Admin/Desktop/dadjoke.py
Traceback (most recent call last):
  File "c:\Users\Admin\Desktop\dadjoke.py", line 9, in <module>
    data = json.loads(str(question.text ))
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads    
    return _default_decoder.decode(s)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode    
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
PS C:\Users\Admin> 

here is my code:

import requests
import json

params = {"q":"joke"}
url = "https://icanhazdadjoke.com"
question = requests.get(url, params)

if question.status_code == 200:
  data = json.loads(str(question.text ))
  print(data)

CodePudding user response:

I've just take a look at the API docs of the website. Accept Header

Since you didn't specify your Accept header, the website will return a HTML response as default

Solution:

headers = {
  "Accept": "application/json"
}
url = "https://icanhazdadjoke.com"

r = requests.get(url, headers = headers)
  • Related