Python program to extract a single value from JSON response - GeeksforGeeks (2024)

Last Updated : 26 Dec, 2022

Improve

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:

Python program to extract a single value from JSON response - GeeksforGeeks (1)

USD To INR

Python program to extract a single value from JSON response - GeeksforGeeks (2)

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)


Python program to extract a single value from JSON response - GeeksforGeeks (3)

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:

Python program to extract a single value from JSON response - GeeksforGeeks (4)

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:

Python program to extract a single value from JSON response - GeeksforGeeks (5)



Like Article

Suggest improvement

Share your thoughts in the comments

Please Login to comment...

Python program to extract a single value from JSON response - GeeksforGeeks (2024)

FAQs

How do I get a specific value from a JSON in Python? ›

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.
  1. 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: ...
  2. Using json. loads() Method. ...
  3. Using JSONDecoder Class. The json. ...
  4. Using orjson Module.
Mar 2, 2024

How to get a specific value from JSON? ›

How to Get a Value from a JSON Array in JavaScript ?
  1. Using the array[index] method.
  2. Using the array[key] method.
  3. Using the array.slice method.
  4. Using for…of the loop.
  5. Using forEach()
  6. Using the map() method.
  7. Using filter() method.
  8. Using the find() method.
Jan 30, 2024

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.

How to query JSON data in Python? ›

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
  1. Add a named element to the body of your page, like this: <div id="weatherDescription"></div>
  2. 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
  1. {"emp_details":[ {"name": "a", "id": "123" }, {"name":"b", "id":"345" } ] } You need to give the file name, so this is my file name. ...
  2. data = json. load(jsonFile) ...
  3. jsonData = data["emp_details"] keys = x. ...
  4. import json with open("test.json") as jsonFile: data = json.
Jan 12, 2021

How do you fetch data from JSON data? ›

1. Using the fetch() API to Read JSON file
  1. Create a JSON file and add data to it.
  2. Open the JavaScript file.
  3. In the fetch method pass the path of the JSON file.
  4. Use the . json() method to parse the data in JSON format.
  5. Display the content in the console.
Jun 6, 2024

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:
  1. import json. # Sample JSON data (in string format)
  2. # Step 1: Use json.loads() to parse the JSON data.
  3. # Step 2: Verify if the parsed data is a list of dictionaries.
  4. # Handle the case where the parsed data is not a list of dictionaries.
Jan 31, 2023

How to get unique values in JSON object Python? ›

Python JSON: Access only unique key value of a Python object
  1. Sample Solution:-
  2. 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) ...
  3. Flowchart:
Aug 19, 2022

Top Articles
Assassin's Creed Valhalla: How To Beat Odin
Drawdown Pension Calculator | Legal & General
The Atlanta Constitution from Atlanta, Georgia
Midflorida Overnight Payoff Address
Rabbits Foot Osrs
Z-Track Injection | Definition and Patient Education
Deshret's Spirit
Pollen Count Los Altos
South Bend Tribune Online
Slmd Skincare Appointment
Guardians Of The Galaxy Vol 3 Full Movie 123Movies
123Moviescloud
Nonuclub
Diablo 3 Metascore
Chastity Brainwash
Adam4Adam Discount Codes
How to Create Your Very Own Crossword Puzzle
Pickswise Review 2024: Is Pickswise a Trusted Tipster?
Self-Service ATMs: Accessibility, Limits, & Features
Sef2 Lewis Structure
‘The Boogeyman’ Review: A Minor But Effectively Nerve-Jangling Stephen King Adaptation
R. Kelly Net Worth 2024: The King Of R&B's Rise And Fall
Pirates Of The Caribbean 1 123Movies
Jeff Nippard Push Pull Program Pdf
Disputes over ESPN, Disney and DirecTV go to the heart of TV's existential problems
BJ 이름 찾는다 꼭 도와줘라 | 짤방 | 일베저장소
Apparent assassination attempt | Suspect never had Trump in sight, did not get off shot: Officials
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
Afni Collections
Free T33N Leaks
Usa Massage Reviews
R/Mp5
Otis Inmate Locator
Pixel Combat Unblocked
Grove City Craigslist Pets
Star News Mugshots
Haunted Mansion Showtimes Near Cinemark Tinseltown Usa And Imax
Pch Sunken Treasures
Helloid Worthington Login
Blue Beetle Movie Tickets and Showtimes Near Me | Regal
Domina Scarlett Ct
Bella Thorne Bikini Uncensored
Publictributes
Doordash Promo Code Generator
Top 40 Minecraft mods to enhance your gaming experience
Random Animal Hybrid Generator Wheel
60 Days From May 31
Unit 11 Homework 3 Area Of Composite Figures
Server Jobs Near
Meee Ruh
Ihop Deliver
Provincial Freeman (Toronto and Chatham, ON: Mary Ann Shadd Cary (October 9, 1823 – June 5, 1893)), November 3, 1855, p. 1
Latest Posts
Article information

Author: Carmelo Roob

Last Updated:

Views: 5411

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.