Last Updated : 26 Dec, 2022
We will discuss how Python can be used to extract a value from a JSON response using API and JSON files.
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.
API Key is available at: https://exchangeratesapi.io/documentation/
Python3
# importing required module
import
urllib.parse
import
requests
# setting the base URL value
First
=
input
(
"Enter First Currency Value"
)
Second
=
input
(
"Enter Second Currency Value"
)
result
=
First
+
"/"
+
Second
final_url
=
baseUrl
+
result
# retrieving data from JSON Data
json_data
=
requests.get(final_url).json()
Final_result
=
json_data[
'conversion_rate'
]
print
(
"Conversion rate from "
+
First
+
" to "
+
Second
+
" = "
, Final_result)
Output:
USD To INR
INR TO EUR
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 librarypip 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
# 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.
Extract values from a JSON File
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]” }
]}
Fetch all Values from JSON file
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.
Python3
import
json
with
open
(
'exam.json'
,
'r'
) as json_File :
sample_load_file
=
json.load(json_File)
print
(sample_load_file)
Output:
Fetch specific Values from the JSON file
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.
Python3
import
json
with
open
(
'exam.json'
,
'r'
) as json_File:
sample_load_file
=
json.load(json_File)
# getting hold of all values inside
# the dictionary
test
=
sample_load_file[
'criteria'
]
# getting hold of the values of
# variableParam
test1
=
test[
1
].values()
test2
=
list
(test1)[
0
]
test3
=
test2[
1
:
-
1
].split(
","
)
print
(test3[
1
])
Output:
Share your thoughts in the comments
Please Login to comment...
FAQs
Fetch specific Values from the JSON file
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.
How to extract a single value from JSON response? ›
Extracting a Single Value from a Local JSON File
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.
How to get specific data from JSON file in Python? ›
After loading JSON data into Python, you can access specific data elements using the keys provided in the JSON structure. In JSON, data is typically stored in either an array or an object. To access data within a JSON array, you can use array indexing, while to access data within an object, you can use key-value pairs.
How to extract data from JSON data in Python? ›
Explanation: JSON data is parsed from a given string.
- 3 Ways to Extract or Parse JSON from a String in Python. Below are some of the ways by which we can parse JSON from a string in Python: ...
- Using json. loads() Method. ...
- Using JSONDecoder Class. The json. ...
- Using orjson Module.
How to get a specific value from JSON? ›
How to Get a Value from a JSON Array in JavaScript ?
- Using the array[index] method.
- Using the array[key] method.
- Using the array.slice method.
- Using for…of the loop.
- Using forEach()
- Using the map() method.
- Using filter() method.
- Using the find() method.
How to extract data from a JSON file? ›
Alternatively, you can employ a command-line tool or script such as jq to quickly and easily filter, query, or transform JSON data. Additionally, you can use a graphical user interface (GUI) tool or application like Postman to visually explore, edit, and extract data from JSON files.
How to parse value from JSON? ›
Example - Parsing JSON
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
How to get attribute from JSON object in Python? ›
A JSON object extracts Attribute by indexing the object by a specific key. For example: the value "John" in json_object = {"id": 10, "name": " John"} is extracted by json_object["name"]. Now, use json. loads() to convert a json object to a dictionary and extract an attribute.
How to parse JSON in Python? ›
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
How do I get specific data from a file in Python? ›
Method 1: fileobject.readlines()
A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.
JSON is JavaScript Object Notation.
Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }. It is similar to the dictionary in Python.
How to print specific data from JSON? ›
Printing a JSON value to the page
- Add a named element to the body of your page, like this: <div id="weatherDescription"></div>
- Inside the tags of your done method, pull out the value you want into a variable, like this: var content = "data. query. results.channel. item. description";
How to get a particular value from a JSON object in Python? ›
Get all keys and values from json object in Python
- {"emp_details":[ {"name": "a", "id": "123" }, {"name":"b", "id":"345" } ] } You need to give the file name, so this is my file name. ...
- data = json. load(jsonFile) ...
- jsonData = data["emp_details"] keys = x. ...
- import json with open("test.json") as jsonFile: data = json.
How do you fetch data from JSON data? ›
1. Using the fetch() API to Read JSON file
- Create a JSON file and add data to it.
- Open the JavaScript file.
- In the fetch method pass the path of the JSON file.
- Use the . json() method to parse the data in JSON format.
- Display the content in the console.
How to write a JSON response to a file in Python? ›
Method 2: Writing data to JSON using json.
JSON can also be written to a file using the json. dump() method. Without first converting the dictionary into a JSON object, the "dump" function of the JSON package simply writes the dictionary to a file in the JSON format. There are two parameters accepted by json.
How to parse a JSON in Python? ›
If you have a JSON string, you can parse it by using the json. loads() method. The result will be a Python dictionary.
How to get value of a key from JSON file in Python? ›
Below is the code if you want to use directly and after code is the explanation:
- import json. # Sample JSON data (in string format)
- # Step 1: Use json.loads() to parse the JSON data.
- # Step 2: Verify if the parsed data is a list of dictionaries.
- # Handle the case where the parsed data is not a list of dictionaries.
How to get unique values in JSON object Python? ›
Python JSON: Access only unique key value of a Python object
- Sample Solution:-
- Python Code: import json python_obj = '{"a": 1, "a": 2, "a": 3, "a": 4, "b": 1, "b": 2}' print("Original Python object:") print(python_obj) json_obj = json.loads(python_obj) print("\nUnique Key in a JSON object:") print(json_obj) ...
- Flowchart: