【问题标题】:From an array of objects, print a list of only one object property (Python)从对象数组中,打印仅包含一个对象属性的列表(Python)
【发布时间】:2020-07-29 06:25:25
【问题描述】:

这是我第一次使用 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'

您能提供的任何帮助将不胜感激。谢谢!

【问题讨论】:

  • users 是一个列表——你想访问一个元素的属性,例如users[0].get('<attribute_name>')

标签: python json api


【解决方案1】:

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

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

这是您可以在 JSON 响应中访问嵌套属性的方式。

您还可以遍历用户并以相同的格式打印他们的城市。

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

【讨论】:

  • 我知道我必须使用 for 循环,但不太清楚提取 city 属性的语法。非常感谢!
【解决方案2】:

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

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

输出:

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

[Program finished]

【讨论】:

    【解决方案3】:
            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   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2019-12-15
      • 1970-01-01
      • 2021-02-15
      • 2023-01-11
      • 2021-10-25
      • 2016-04-16
      相关资源
      最近更新 更多