我是 Python 的新手。我有一個收集 API 呼叫資料的專案。我已經根據這篇文章成功呼叫了一個資料串列(用戶串列和其他資訊,如 ID、姓名、.....):回圈遍歷物件的屬性并獲取 DateTime 型別的值。我制作的代碼如下所示:
import requests
import json
def get_all_time_entries():
url_address = "my url"
headers = {
"Authorization": "Bearer " "my api",
"Harvest-Account-ID": "my ID"
}
all_time_entries = []
# loop through all pages and return JSON object
for page in range(1, 15):
url = "my url" str(page)
response = requests.get(url=url, headers=headers).json()
all_time_entries.append(response)
page = 1
# prettify JSON
data = json.dumps(all_time_entries, sort_keys=True, indent=4)
return data
print(get_all_time_entries())
我設法呼叫了這種格式的用戶串列:
{
"created_at": "2021-01-23T22:34:30 07:00",
"email": "someone.gmail.com",
"id": 11111,
"integration_id": null,
"login_id": "someone.gmail.com",
"name": "Name of user",
"short_name": "Name of user",
"sis_import_id": 111,
"sis_user_id": "Name of user",
"sortable_name": ", Name of user"
},
現在我想做一個回圈來獲取“all_time_entries()”串列中的所有“ID”屬性并將它們放在另一個串列中。是否可以?或者有什么解決方案嗎?非常感謝。
uj5u.com熱心網友回復:
洗掉回圈末尾的“page = 1”,每次迭代頁面的值在開始時分配給其相應的范圍值,要獲取所有id,請執行以下操作:
all_ids = [i['id'] for i in all_time_entries]
uj5u.com熱心網友回復:
以下功能將執行您想要的操作
get_ids_from_time_entries(time_entries):
ids = []
for entry in time_entries:
ids.append( entry['id'] )
return ids
然后你會像這樣使用它
time_entries = get_all_time_entries()
ids = get_ids_from_time_entries(time_entries)
print(ids)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/337987.html
