json library
Lesson 4 of 7 in Coddy's Random Fact Generator - Python Project course.
After we have the content in a string format, we want to extract the fact itself.
Maybe you noticed, but the content is in a format called JSON, and we will use the json library to extract the content from it.
The json library, converts a string in a JSON format to a Python dictionary:
import json
data = json.loads("some json formatted text")In the end, data will hold a valid Python dictionary!
Challenge
EasyIn the function body, after you get the content from the API, convert it to Python dictionary and extract the fact (which attribute holds it?) return it in the end.
You can check here the format to understand better what attribute you are looking for:
https://uselessfacts.jsph.pl/api/v2/facts/random
Don't forget to
import json
Try it yourself
import requests
def get_fact():
response = requests.get('https://uselessfacts.jsph.pl/api/v2/facts/random')
content = response.text
return content