In this tutorial, we’ll learn how to extract value from a JSON response using Python. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate.
It is a popular format for exchanging data in modern web applications. In Python, we can use the JSON module to parse and extract values from JSON data.
Step 1: Importing the JSON module
The first step is to import the JSON module. This module comes pre-installed with Python and doesn’t require any additional installation. You can import it using the following command:
1 |
import json |
Step 2: Convert JSON data to Python object
We will use the json.loads()
method to convert the JSON data to a Python object. This will help us easily access the data in Python.
1 2 |
json_data = '{"name": "John", "age": 30, "city": "New York"}' python_obj = json.loads(json_data) |
In this example, json_data
is a string that represents JSON data. The json.loads()
method takes a valid JSON string and converts it into a Python object, which we store in the python_obj
variable.
Step 3: Accessing a specific value from the JSON data
Now that we have the JSON data loaded as a Python object, we can access and extract specific values using the appropriate data structure operations. In this case, we have a dictionary.
1 |
name = python_obj["name"] |
In this example, we extract the value of the "name"
key from the Python dictionary python_obj
. The extracted value is stored in the name
variable.
Step 4: Print the extracted value
Finally, we can print the extracted value using the print
function.
1 |
print("Name:", name) |
This will print the extracted value of the name key from the JSON data.
Full Example Code
1 2 3 4 5 6 7 8 |
import json json_data = '{"name": "John", "age": 30, "city": "New York"}' python_obj = json.loads(json_data) name = python_obj["name"] print("Name:", name) |
Output
Name: John
Conclusion
In this tutorial, we have learned how to extract values from a JSON response using Python.
We used the JSON module to parse and load the JSON data into a Python object and then accessed specific values from the object as needed. This method is useful when working with APIs and web applications that return data in JSON format.