Method-2

Using the jsonpath-ng library to extract values from the JSON response. jsonpath-ng is a fork of the jsonpath library and allows for more powerful querying of JSON data using expressions similar to those used in XPath.

# install jsonpath-ng library
pip install jsonpath-ng

Here’s an example of how you could use jsonpath-ng to extract the conversion rate from the JSON response in the first example:

Python3




# import required libraries
import urllib.parse
import requests
from jsonpath_ng import jsonpath, parse
 
# setting the base URL value
baseUrl = "https://v6.exchangerate-api.com/v6/0f215802f0c83392e64ee40d/pair/"
 
# ask user to enter currency values
First = input("Enter First Currency Value: ")
Second = input("Enter  Second Currency Value: ")
 
# combine base URL with final URL including both currencies
result = First+"/"+Second
final_url = baseUrl+result
 
# send API call and retrieve JSON data
json_data = requests.get(final_url).json()
 
# set up jsonpath expression to select conversion rate
jsonpath_expr = parse('$.conversion_rate')
 
# use jsonpath expression to extract conversion rate
result = jsonpath_expr.find(json_data)[0].value
print("Conversion rate from "+First+" to "+Second+" = ", result)



Output

Using jsonpath-ng can make it easier to extract specific values from complex JSON structures without having to manually navigate through the data.

Python program to extract a single value from JSON response

We will discuss how Python can be used to extract a value from a JSON response using API and JSON files.

Similar Reads

Extract value from the JSON response using the API

Initially, use the API Key variable to declare the base URL. Where the first currency needs to be converted with the second, ask the user to enter a currency name and save it in a variable. The base URL is combined with the final URL, which includes both currencies, to fetch the result. An API call is then sent. The data is obtained by accessing the JSON Data’s “conversion rate” key, and the resulting conversion rate is then printed....

Method-2:

...

Extract values from a JSON File

Using the jsonpath-ng library to extract values from the JSON response. jsonpath-ng is a fork of the jsonpath library and allows for more powerful querying of JSON data using expressions similar to those used in XPath....

Contact Us