从对象数组中,仅打印一个对象属性的列表(Python)

2024-09-29 01:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次使用Python,我的任务是:从这个JSON打印城市列表:http://jsonplaceholder.typicode.com/users

我正在打印一份清单,上面应该写着: 格温伯勒 维索克伯格 麦肯齐黑文 南猫王 等等

这是我目前掌握的代码:

import json
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)
print(users)

当我运行$python3 -i api.py(文件名为api.py)时,我能够从终端中的JSON文件打印列表。然而,我一直在试图找出如何只打印城市。我假设它看起来像users.address.city,但任何试图找出代码的尝试都会导致以下错误:AttributeError: 'list' object has no attribute 'address'

如果您能提供任何帮助,我们将不胜感激。谢谢


Tags: 代码pyimportcomapijsonhttp列表
3条回答

您可以使用用户['address']['city']获取城市名称 并使用循环获取所有城市名称 像这样

for user in users:
    print(user['address']['city'])

输出:

Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
Roscoeview
South Christy
Howemouth
Aliyaview
Bartholomebury
Lebsackbury

[Program finished]

由于users是一个列表,它应该是:

print(users[0]['address']['city'])

这就是如何访问JSON响应中的嵌套属性

您还可以循环浏览用户并以相同的格式打印他们的城市

for user in users:
    print(user['address']['city'])
        first of all i get this, why your loading(response.text) , instead requests package has a built in .json() method which is what you want to access nested data . so you could do something like this 
        
        response = requests.get("https://jsonplaceholder.typicode.com/users")
        data = response.json()
        
        # optional
        print(data)
        
        * loop through the addresses to get all the cities 
   for dt in data['address']:
    # do what you want with the data returned   

相关问题 更多 >