Level 1
0 / 100 XP

Working with JSON

In this lesson you are going to learn more about working with JSON objects that HTTP. Let's start with the following HTTP get request:

Python
import requests # Make a GET request to the endpoint response = requests.get("https://jsonplaceholder.typicode.com/todos/1") # Print the entire response print(response.json())

The response.json() method is used to convert the response of an HTTP request to a JSON object. This is often useful when working with APIs that return JSON data, as it allows us to easily access and manipulate the data in our Python code.

In the example code you provided, we are making a GET request to the https://jsonplaceholder.typicode.com/todos/1 endpoint using the requests module. This endpoint returns a JSON object representing a to-do item with an ID of 1.

Python JSON vs Dictionary?

The main difference between Python dictionaries and JSON objects is the way they are structured. In Python, a dictionary is a collection of key-value pairs, where the keys must be unique and are usually strings. In JSON, an object is a collection of key-value pairs, where the keys must be strings and the values can be of any data type (including other objects or arrays).

Accessing data inside of the dictionary object

For example, to access the "title" of the to-do item, we can use the following code:

Python
# Print the response data = response.json() # Parse the JSON into a dictionary named 'data' title = data["title"] # Extract the title key value print(title) # Print the value

This will retrieve the value associated with the "title" key, which in this case is "delectus aut autem".

We can also loop through the keys and values of the dictionary to do more complex manipulations of the data. For example:

Text
# Print the response data = response.json() # Loop through the keys and values in the dictionary for key, value i…