Backend Development 5 min read

Extracting Specific Keys from JSON Lists and Downloading Images with Python

This article explains how to extract a particular key from each JSON object in a list, optionally filter out unwanted entries, and download images from URLs using Python's requests and os modules, providing complete example code for both tasks.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Extracting Specific Keys from JSON Lists and Downloading Images with Python

The article begins by describing a Python function def extract_key_from_json_list(json_list, key): extracted_list = [] for json_obj in json_list: if key in json_obj: extracted_list.append(json_obj[key]) return extracted_list that iterates over a list of JSON objects, checks for the presence of a specified key, and builds a new list containing the corresponding values.

An example demonstrates extracting the "name" field from a sample list of dictionaries, producing ['Alice', 'Bob', 'Charlie'] as output.

The article then introduces a second function for downloading images: import os import requests def download_images(image_list, output_folder): if not os.path.exists(output_folder): os.makedirs(output_folder) for index, image_url in enumerate(image_list): try: response = requests.get(image_url) response.raise_for_status() file_name = str(index) + '.jpg' # numeric index as filename file_path = os.path.join(output_folder, file_name) with open(file_path, 'wb') as file: file.write(response.content) print(f"Downloaded {file_name}") except requests.exceptions.RequestException as e: print(f"Error downloading image at index {index}: {str(e)}") # Example usage image_urls = [ 'https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg' ] output_folder = 'images' # folder to store images download_images(image_urls, output_folder) . This function creates the target folder if needed, iterates over the URL list with enumerate , downloads each image, saves it with a numeric filename, and logs success or errors.

Finally, an extended version of the extraction function shows how to exclude JSON objects where the type field equals 3: def extract_key_from_json_list(json_list, key): extracted_list = [] for json_obj in json_list: if json_obj.get('type') != 3 and key in json_obj: extracted_list.append(json_obj[key]) return extracted_list . An example list with various type values demonstrates that the function returns only the names of objects whose type is not 3.

backendData Processingscriptingimage-downloading
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.