How To Get Specific Value From JSON Object In Python

Working with JSON (JavaScript Object Notation) is a common requirement when dealing with RESTful APIs, data storage, or even configuration files.

Python includes a built-in package called json that allows working with JSON data in a straightforward and efficient way. In this tutorial, we will cover how to get a specific value from a JSON object in Python using various methods.

Step 1: Read JSON Data

First, let’s create a sample JSON object for illustration purposes. You can replace it with your own JSON object either by loading from a file or fetching from an API.

Now we need to parse this JSON data into a Python dictionary. We will use the loads() function from the json package to accomplish this. If you are reading the JSON data from a file, you can use the load() function instead.

Step 2: Access JSON Object Value Directly

If you know the path to the specific value in your JSON object, you can access it directly using the key of the dictionary. For example, to access the “name” and “city” of the person in the JSON object, you can simply do:

This would display:

Name: John
City: New York

Step 3: Access Nested JSON Object Values

To access nested JSON object values, you can chain the keys using the dictionary indexing. For example, to access “email” and “phone” from the “contacts” object, you can do:

This would display:

Email: [email protected]
Phone: 555-123-456

Step 4: Access JSON Array Values

To access values from a JSON array, simply use the index of the element. For example, to access the first and last hobbies in the “hobbies” array, you can do:

This would display:

First hobby: reading
Last hobby: hiking

Full Code:

Output:

Name: John
City: New York
Email: [email protected]
Phone: 555-123-456
First hobby: reading
Last hobby: hiking

Conclusion

In this tutorial, we learned how to get specific values from a JSON object in Python using the built-in json package. We can now access values directly, nested values, and even values within arrays. This skill is essential when working with JSON data from APIs or other sources.