1

So I am using a riddle API and whenever it is ran it outputs it data like this:

  [
  {
    "title": "The Magic House",
    "question": "There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?",
    "answer": "bathroom"
  }
  ]

How could I convert the title, question and answer from the API output into 3 different variables that could then be used in a program.

If the API outputs that the Title =A ,the question = B, and answer = C ,then how would I make it so that in my code, Variable1=A,Variable2=B and Variable3=C?

The API comes from API ninjas and here is the code provided with it:

import requests

api_url = 'https://api.api-ninjas.com/v1/riddles'
response = requests.get(api_url, headers={'X-Api-Key': 'YOUR_API_KEY'})
if response.status_code == requests.codes.ok:
    print(response.text)
else:
    print("Error:", response.status_code, response.text)

How would I do this with the code provided?

1 Answer 1

1

The response you received from the server looks like JSON so use json module to parse it. When you parse the response, you access the items like normal python list/dict:

import json

response_text = """[
  {
    "title": "The Magic House",
    "question": "There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?",
    "answer": "bathroom"
  }
]"""

data = json.loads(response_text)

for item in data:
    print("Title =", item["title"])
    print("Question =", item["question"])
    print("Answer =", item["answer"])

print(data)

Prints:

Title = The Magic House
Question = There is a house,if it rains ,there is water in it and if it doesn't rain,there is water in it.what kind of house is that?
Answer = bathroom
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.