![]() |
VOOZH | about |
We will discuss how Python can be used to extract a value from a JSON response using API and JSON files.
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.
API Key is available at: https://exchangeratesapi.io/documentation/
Output:
The 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-ngHere's an example of how you could use jsonpath-ng to extract the conversion rate from the JSON response in the first example:
Using jsonpath-ng can make it easier to extract specific values from complex JSON structures without having to manually navigate through the data.
To create a JSON file open a text editor either notepad or VSCode then copy the above code and save the code with the .json extension.
{"criteria": [
{"locationParam": "[ALL:03232434]" },
{"variableParam": "[00060, 00065]" }
]}
Import JSON from the modules. Open the JSON file in read-only mode and load the JSON data into a variable using the Python load() function. Print the variable where the JSON data is loaded. The load function stores the JSON data as a Python dictionary of key-value pairs.
Output:
Import JSON from the modules. Open the JSON file in read-only mode using the Python with() function. Load the JSON data into a variable using the Python load() function. Now, get the value of keys in a variable. Now convert the value of the dictionary into a list and slice the string using the split function.
Output: