Skip to content
Advertisement

How to check for what JSON data exists in a Python HTTP Request?

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:

import requests
import json

def getJoke():
  response = requests.get("https://v2.jokeapi.dev/joke/Any")
  print(response.text)
  json_data = json.loads(response.text)
  joke = json_data['joke'] + json_data['setup'] + " " + json_data['delivery']
  print(joke)

getJoke()

Some of the responses are

    "error": false,
    "category": "Christmas",
    "type": "twopart",
    "setup": "How will Christmas dinner be different after Brexit?",
    "delivery": "No Brussels!",

and

    "error": false,
    "category": "Programming",
    "type": "twopart",
    "joke": "Why is Linux safe?",
    "delivery": "Hackers peak through Windows only.",

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:

{
    "error": false,
    "category": "Pun",
    "type": "single",
    "joke": "To whoever stole my copy of Microsoft Office, I will find you. You have my Word!",
    "flags": {
        "nsfw": false,
        "religious": false,
        "political": false,
        "racist": false,
        "sexist": false,
        "explicit": false
    },
    "id": 191,
    "safe": true,
    "lang": "en"
}

Multiple part joke:

{
    "error": false,
    "category": "Programming",
    "type": "twopart",
    "setup": "Why do programmers prefer using the dark mode?",
    "delivery": "Because light attracts bugs.",
    "flags": {
        "nsfw": false,
        "religious": false,
        "political": false,
        "racist": false,
        "sexist": false,
        "explicit": false
    },
    "id": 232,
    "safe": true,
    "lang": "en"
}

You need to check the joke type prior to querying the other json elements.

import requests
import json

def getJoke():
  response = requests.get("https://v2.jokeapi.dev/joke/Any")
  json_data = json.loads(response.text)
  joke_type = json_data['type']
  if joke_type == 'single':
      joke = json_data['joke']
  elif joke_type == 'twopart':
    joke_setup = json_data['setup']
    joke_delivery = json_data['delivery']
    print (f'Joke Setup: {joke_setup} nJoke Delivery: {joke_delivery}')
    # output
    Joke Setup: Why does Dr. Pepper come in a bottle?
    Joke Delivery: His wife is dead.


getJoke()
Advertisement