Python program to extract a single value from JSON response

Python program to extract a single value from JSON response

Below is a simple Python program that extracts a single value from a JSON response. In this example, we'll use the requests module to make an HTTP request and the built-in json module to handle the JSON response.

First, if you haven't already, install the requests module:

pip install requests 

Then, here's a basic example that fetches a JSON response and extracts a specific value:

import requests import json # Make an HTTP request response = requests.get("https://api.example.com/data") # Ensure we got a successful response response.raise_for_status() # Parse the JSON content data = response.json() # Extract a specific value (for this example, let's say we want to extract the 'name' value) name = data.get("name") print("Extracted Name:", name) 

Note: This assumes the JSON response looks something like:

{ "name": "John Doe", "age": 30, "location": "New York" } 

However, if the desired value is nested inside another object or an array, you'd need to navigate through the structure accordingly. For instance, if the response is:

{ "user": { "name": "John Doe", "age": 30 }, "location": "New York" } 

To extract the name, you'd use:

name = data["user"]["name"] 

Modify the example to fit your actual JSON structure and the specific value you want to extract.


More Tags

ip-address ssl eventtrigger jasper-reports http-patch typeorm network-analysis rightbarbuttonitem http-headers debian-based

More Programming Guides

Other Guides

More Programming Examples