I’m working on a script with Python that will generate a joke using an API I found online. (https://sv443.net/jokeapi/v2/). However, some of the setup/question parts of the joke use JSON Data, which varies between being ‘setup’ and ‘joke’. I’m looking to see if I can write a script that will check which one the response is pulling. I have my script here:
JavaScript
x
12
12
1
import requests
2
import json
3
4
def getJoke():
5
response = requests.get("https://v2.jokeapi.dev/joke/Any")
6
print(response.text)
7
json_data = json.loads(response.text)
8
joke = json_data['joke'] + json_data['setup'] + " " + json_data['delivery']
9
print(joke)
10
11
getJoke()
12
Some of the responses are
JavaScript
1
6
1
"error": false,
2
"category": "Christmas",
3
"type": "twopart",
4
"setup": "How will Christmas dinner be different after Brexit?",
5
"delivery": "No Brussels!",
6
and
JavaScript
1
6
1
"error": false,
2
"category": "Programming",
3
"type": "twopart",
4
"joke": "Why is Linux safe?",
5
"delivery": "Hackers peak through Windows only.",
6
Is there a way to check which data-name the response is getting?
Advertisement
Answer
There are two types of jokes. Single liners and multiple part ones.
Single line joke:
JavaScript
1
18
18
1
{
2
"error": false,
3
"category": "Pun",
4
"type": "single",
5
"joke": "To whoever stole my copy of Microsoft Office, I will find you. You have my Word!",
6
"flags": {
7
"nsfw": false,
8
"religious": false,
9
"political": false,
10
"racist": false,
11
"sexist": false,
12
"explicit": false
13
},
14
"id": 191,
15
"safe": true,
16
"lang": "en"
17
}
18
Multiple part joke:
JavaScript
1
19
19
1
{
2
"error": false,
3
"category": "Programming",
4
"type": "twopart",
5
"setup": "Why do programmers prefer using the dark mode?",
6
"delivery": "Because light attracts bugs.",
7
"flags": {
8
"nsfw": false,
9
"religious": false,
10
"political": false,
11
"racist": false,
12
"sexist": false,
13
"explicit": false
14
},
15
"id": 232,
16
"safe": true,
17
"lang": "en"
18
}
19
You need to check the joke type prior to querying the other json elements.
JavaScript
1
20
20
1
import requests
2
import json
3
4
def getJoke():
5
response = requests.get("https://v2.jokeapi.dev/joke/Any")
6
json_data = json.loads(response.text)
7
joke_type = json_data['type']
8
if joke_type == 'single':
9
joke = json_data['joke']
10
elif joke_type == 'twopart':
11
joke_setup = json_data['setup']
12
joke_delivery = json_data['delivery']
13
print (f'Joke Setup: {joke_setup} nJoke Delivery: {joke_delivery}')
14
# output
15
Joke Setup: Why does Dr. Pepper come in a bottle?
16
Joke Delivery: His wife is dead.
17
18
19
getJoke()
20