You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 city correctly—since it's nested under the address key in each user entry, we use user['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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:46:50