簡體   English   中英

我如何訪問和操作 api 值

[英]How do i access and manipulate the api values

我想了解如何訪問數據並進行一些修改等,例如僅訪問和列出電子郵件等

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

data_structure = []
data_structure.append(x)


print(data_structure)

Output [{'page': 2, 'per_page': 6, 'total': 12, 'total_pages': 2, 'data': [{'id': 7, 'email': 'michael.lawson@reqres. in','first_name':'Michael','last_name':'Lawson','avatar':'https://reqres.in/img/faces/7-image.jpg'},{'id':8 ,'電子郵件':'lindsay.ferguson@reqres.in','first_name':'Lindsay','last_name':'Ferguson','頭像':'https://reqres.in/img/faces/8- image.jpg'}, {'id': 9, 'email': 'tobias.funke@reqres.in', 'first_name': 'Tobias', 'last_name': 'Funke', 'avatar': 'https: //reqres.in/img/faces/9-image.jpg'}, {'id': 10, 'email': 'byron.fields@reqres.in', 'first_name': 'Byron', 'last_name' :'字段','頭像':'https://reqres.in/img/faces/10-image.jpg'},{'id':11,'電子郵件':'george.edwards@reqres.in' , 'first_name': 'George', 'last_name': 'Edwards', '頭像': 'https://reqres.in/img/faces/11-image.jpg'}, {'id': 12, '電子郵件':'rachel.howell@reqres.in','first_name':'Rachel','last_name':'Howell','頭像':'https://reqres.in/img/faces/12-image。 jpg'}],'s upport': {'url': 'https://reqres.in/#support-heading', 'text': '為了保持 ReqRes 免費,感謝您對服務器成本的貢獻!'}}]

首先,我強烈建議您安裝 JSON 查看器擴展,它將幫助您了解 API 發生了什么。

https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh?hl=es

然后,您不需要創建新列表,因為 x = test.json() 已經輸出了您從 API 帶來的同一個字典。

所以你的第一塊代碼應該是這樣的

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

然后您可以訪問該字典中的所有數據,例如讓我們獲取所有電子郵件。

為了更容易,您應該使用 JSON 查看器將 go 連接到 api 鏈接以查看字典的結構。

要訪問電子郵件,我們首先需要訪問字典上的“數據”鍵

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

data_list = x["data"]

之后,您可以看到 data_list 是一個新的字典列表,其中包含 API 上每個元素的所有數據(在您的情況下是每個 id)。

所以最后,要訪問電子郵件,我們需要遍歷該列表並從列表中的每個字典中獲取“電子郵件”鍵。

import requests,json

api = "https://reqres.in/api/users?page=2"

test = requests.get(api)
x = test.json()

data_list = x["data"]

for i in data_list:
    print(i["email"])

我的朋友,就是你從 API 獲取信息的方式,就像你操作列表和字典一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM