Python3:从JSON接口提取并格式化输出指定用户字段
Hey there! I see you've already nailed the data fetching part—great start! Let's tweak your code to pull out those specific fields and display them in a clean, easy-to-read list.
First, a quick note: your current print(r) just outputs the request response object (like <Response [200]>), which isn't the actual user data. You already parsed the JSON into data, so we can work directly with that. Also, you don't need the json import since requests' built-in .json() method handles parsing for you.
Here's the revised code that extracts name, email, city, and phone for each user, with a polished output format:
import requests # Fetch and parse the user data from the API r = requests.get('https://jsonplaceholder.typicode.com/users') data = r.json() # Print formatted user list print("=== User Directory ===\n") for user_num, user in enumerate(data, start=1): print(f"User #{user_num}") print(f"* Name: {user['name']}") print(f"* Email: {user['email']}") print(f"* City: {user['address']['city']}") # City is nested inside the 'address' object print(f"* Phone: {user['phone']}\n")
What this code does:
- Uses
enumerate()to add a user number (starting at 1) for better readability. - Accesses
citycorrectly—since it's nested under theaddresskey in each user entry, we useuser['address']['city']to reach it. - Adds separators and line breaks to keep the output organized and visually clean.
If you prefer a more compact bullet-point style, you can use this version instead:
import requests r = requests.get('https://jsonplaceholder.typicode.com/users') data = r.json() print("### User List ###") for user in data: print(f"- **{user['name']}**") print(f" - Email: {user['email']}") print(f" - City: {user['address']['city']}") print(f" - Phone: {user['phone']}\n")
Either version will give you the structured, aesthetic output you're looking for. Let me know if you hit any bumps!
内容的提问来源于stack exchange,提问作者Neal

