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) |
Using jsonpath-ng can make it easier to extract specific values from complex JSON structures without having to manually navigate through the data.
Contact Us