这是我第一次使用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'
如果您能提供任何帮助,我们将不胜感激。谢谢
您可以使用用户['address']['city']获取城市名称 并使用循环获取所有城市名称 像这样
输出:
由于
users
是一个列表,它应该是:这就是如何访问JSON响应中的嵌套属性
您还可以循环浏览用户并以相同的格式打印他们的城市
相关问题 更多 >
编程相关推荐