Write a Python program that uses the json module to read a JSON file and print the data. The function print_json_data(filename) should accept the filename as an argument and print the contents of the file. You can use a json file on your local environment or on Trinket you can use the following code to get json data from JSONPlaceholder:
import requests # URL for the JSON data url = "https://jsonplaceholder.typicode.com/users" # Make a GET request to the URL response = requests.get(url) # Convert the response to JSON data = response.json()
Example:
Input: print_json_data("sample.json") Output: Prints the contents of the file "sample.json"
Use the json.load()
function from the json
module.
import json def print_json_data(filename): with open(filename, 'r') as f: data = json.load(f) print(data) # Test the function # Ensure there is a sample.json file in your working directory before testing print_json_data("sample.json")
Unlock AI & Data Science treasures. Log in!