Open In App

Python program to extract a single value from JSON response

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 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
 
# 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:

 



Previous Article
Next Article

Similar Reads

How to read a JSON response from a link in Python?
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. These libraries have objects and functions which he
2 min read
response.json() - Python requests
Python requests are generally used to fetch the content from a particular resource URL. Whenever we make a request to a specified URL through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.json() out of a r
3 min read
Filtering Json Response With Python List Comprehension
JSON (JavaScript Object Notation) is a widely used data interchange format, and working with JSON responses is a common task in many programming scenarios. In Python, list comprehensions provide a concise and efficient way to filter and manipulate data. In this article, we will explore five simple and commonly used methods for filtering JSON respon
2 min read
Google Geo-coding Web Service (JSON response)
Prerequisite : JSON Formatting in Python Google has an excellent web service that allows us to make use of their large database of geographic information. Here, we are going to be working with the Google Maps API. In the old days, this Maps API was free and did 2, 500 requests per day but now they've made it so that parts of it are behind API keys
4 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural sty
3 min read
Scraping a JSON response with Scrapy
Scrapy is a popular Python library for web scraping, which provides an easy and efficient way to extract data from websites for a variety of tasks including data mining and information processing. In addition to being a general-purpose web crawler, Scrapy may also be used to retrieve data via APIs. One of the most common data formats returned by AP
2 min read
Python - Extract ith Key's Value of K's Maximum value dictionary
Given Dictionary List, extract i'th keys value depending upon Kth key's maximum value. Input : test_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}], K = "best", i = "is" Output : 11 Explanation : best is max at 19, its corresponding "is" value is 11. Input : test_list = [{"Gfg" :
9 min read
Extract JSON from HTML using BeautifulSoup in Python
In this article, we are going to extract JSON from HTML using BeautifulSoup in Python. Module neededbs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.pip install bs4requests: Request allows you to send HTTP/1
3 min read
Extract Multiple JSON Objects from one File using Python
Python is extremely useful for working with JSON( JavaScript Object Notation) data, which is a most used format for storing and exchanging information. However, it can become challenging when dealing with multiple JSON objects stored within a single file. In this article, we will see some techniques to easily extract multiple JSON Objects from a fi
3 min read
How to Extract or Parse JSON from a String in Python
Here, we are given a string and we have to parse JSON format from the string in Python using different approaches. In this article, we will see how we can parse JSON from a string in Python. Example: Input: json_string = '{"India": "Delhi", "Russia": "Moscow", "Japan": "Tokyo"}' Output: {'India': 'Delhi', 'Russia ': 'Moscow ', 'Japan': 'Tokyo'} Exp
3 min read