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

时间:2020-07-29 06:25:25

标签: python json api

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

我正在尝试打印一份清单,内容应为: 格温伯勒 Wisokyburgh 麦肯齐海文 南猫王 等

这是我到目前为止的代码:

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'

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

3 个答案:

答案 0 :(得分:0)

由于users是一个列表,因此应为:

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

这是在JSON响应中访问嵌套属性的方法。

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

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

答案 1 :(得分:0)

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

const arrMap = new Map();
const arr = [
  [1, 2, 3],
  [4, 5, 6]
];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].length; j++) {
    arrMap.set(JSON.stringify([i, j]), arr[i][j]);
  }
}
console.log(arrMap.get(JSON.stringify([1, 1]))); // 5

输出:

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

答案 2 :(得分:0)

        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