Value extraction is a very popular programming concept that is used in a wide variety of operations. However, extracting values from a JSON response is a different concept. It helps us build logic and locate specific values in complex data sets. This article explains the various methods that can be used to extract a single value from a JSON response. Before we start value extraction, let’s focus on what the JSON response means.
JSON (JavaScript Object Notation) responses are a widely accepted data format through which servers respond to client requests . Whenever a client requests some API or information from the server, a response is generated and API is passed to the client. Now, this information is shared in a way that both client and server can understand the data, and for this we need a unified data format.
JSON responses share information in the form of JSON objects that can be converted to any native programming language. Since we are using python and our task is to retrieve a single value from this response, we convert these objects into dictionaries. Now that we have a brief knowledge of JSON responses, let’s understand the extraction part.
In this method we will retrieve data from the server using the API endpoint. First, we will import the "requests" library to handle HTTP requests. We will then send a "GET" request to the API endpoint using the "get()" method. In this example, we will use the "CoinDesk" API endpoint to get the Bitcoin Price Index (BPI) in real time. A JSON object is converted into a dictionary with the help of the "json()" method. These dictionaries are then parsed to select specific information.
Here we will extract the BPI value by accessing the nested object. Dictionary keys refer to certain attributes and properties, and their values refer to different data types. We will use keys to extract single and multiple values. Please refer to this link for official documentation - https://apipheny.io/free-api/
API URL link - https://api.coindesk.com/v1/bpi/currentprice.json
The following is an example of extracting a single value from a JSON response using the "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}")
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
This method focuses on extracting a single value from a JSON file stored on the system. We will first create a JSON file and then import the JSON module to decode the data retrieved from the "JASON Response".
This approach is similar to the file processing concept, we load the JSON file and then open it in a specific mode. We can also change this file and manipulate its contents with the help of different file modes such as Append, Binary, Read Only, etc. We will use a local file (DSC.json) to store information related to the cat, and we will extract this information from a key named "fact".
The 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")
Here is a fact related to cats: Mountain lions are strong jumpers, thanks to muscular hind legs that are longer than their front legs.
We can also convert the JSON data to a string instead of a dictionary by dumping the "JSON Object" into an element and then loading it into a character with the help of ".JSON" String in. load()" method. The most common mistake programmers make while using the value extraction concept is that they use the wrong key name to access the value. Furthermore, when dealing with nested objects, we must Use the correct order to extract the data. Here is an example –
data = Json_data["Parent object"]["Child object"]
This is the hierarchy followed when extracting the correct value.
In this article, we introduced the basics of value extraction and understood its importance. We also discussed the mechanics of a "JSON response" and how to extract individual values from it. In the first method, we retrieve data from the server using the API endpoint. In the second nd approach, we extract the values directly from the locally stored JSON file.
The above is the detailed content of Python program to extract single value from JSON response. For more information, please follow other related articles on the PHP Chinese website!