Python program to extract a single value from JSON response


Value extraction is a very popular programming concept and it is used in a wide variety of operations. However extracting values from a JSON response is a different concept all together. It helps us to build logic and target specific values in a complex dataset. This article will explain the various methods that can be used to extract a single value from a JSON response. Before we start with value extraction, let’s focus on understanding the meaning of a JSON response.

What is a JSON Response?

A JSON (JavaScript Object Notation) response is a widely accepted data format through which a server responds to a client’s request. Whenever a client requests for certain API’s or information from the server, a response is generated and the APIs are delivered to the client. Now this information is shared in a manner such that both the client and the server could understand the data and for this we need a unified data format.

A JSON response shares information in the form of JSON objects that can be converted into any local programming language. Since we are using python and our task is to retrieve a single value from this response, we will convert these objects into dictionaries. Now that we have a brief knowledge about a JSON response, let’s understand the extraction part.

Using APIs to Extract Values from a JSON Response

In this approach, we will use an API endpoint to retrieve data from the server. Firstly, we will import the “requests” library to handle the HTTP request. We will then use the “get()” method to send a “GET” request to an API endpoint. In this example, we will use the “CoinDesk” API endpoint that fetches the bitcoin price index (BPI) in real-time. The JSON objects are converted into dictionaries with the help of “json()” method. These dictionaries are then parsed to pick specific information.

Here, we will extract the BPI value by accessing the nested objects. The dictionary keys refer to certain attributes and properties and their values refer to different data types. We will use the keys to extract single and multiple values. Refer to this link for official documentation − https://apipheny.io/free-api/

The API URL link −https://api.coindesk.com/v1/bpi/currentprice.json

Example

Following is an example to extract a single value from a JSON response using an “CoinDesk” API -

import requests

print("Welcome to the live bitcoin Price index")
Json_data = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json').json()

Disclaimer = Json_data["disclaimer"]
print(Disclaimer)

BPI = Json_data["bpi"]["USD"]["rate"]
print(f"The real time BPI value for the United states of America is: {BPI}")

TIME = Json_data["time"]["updated"]
print(f"The index was viewed at Universal time: {TIME}")

Output

Welcome to the live bitcoin Price index
This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org
The real time BPI value for the United states of America is: 25,978.6344
The index was viewed at Universal time: Jun 11, 2023 18:26:00 UTC

Extracting a Single Value from a Local JSON File

This approach focuses on extracting a single value from a JSON file stored on the system. We will firstly create a JSON file and then import the JSON module for decoding the retrieved data from a “JASON response”.

This approach is similar to the file handling concept where we load a JSON file and then open it in a specific mode. We can also make changes to this file and manipulate its contents with the help of different file modes such as “append”, “Binary”, “Read only” etc. We will be using a local file (DSC.json) that stores information related to cats and we will extract this information from a key named “fact”.

Example

Following is an example −

import json

try:
   with open("DSC.json", "r+") as file:
      Json_file = json.load(file)
   FACTS = Json_file["fact"]
   print(f"Here is a fact related to cats: \n{FACTS}")

except:
   print("File does not exist")

Output

Here is a fact related to cats: 
Mountain lions are strong jumpers, thanks to muscular hind legs that are longer than their front legs.

Other Insights

We can also convert the JSON data into a string instead of a dictionary by dumping the “JSON object” into an element and then load it into a string with the help of “.loads()” method. The most common mistake programmers commit while using this concept of value extraction is that they use the wrong key name to access the values. Also, while dealing with nested objects, we have to use the correct order for data extraction. Following is an example –

data = Json_data["Parent object"]["Child object"]

This is the hierarchy which is followed to extract the correct values.

Conclusion

During the course of this article, we covered the basics of value extraction and understood its significance. We also discussed the mechanism of a “JSON response” and how we can extract a single value from it. In this 1st approach, we used API endpoints to retrieve data from the server. In the 2nd approach, we extracted values directly from a locally stored JSON file.

Updated on: 12-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements