我使用 pytest 在 api 调用上有一个很大的 json 响应。我想获取所有 hpsId 和所有 id 并将其“存储在某处”以用作后续请求中的参数。
[
{
"hpsId": 10032,
"powerPlant": {
"name": "Svartisen",
"id": 67302,
"regionId": 40,
"priceArea": 4,
"timeSeries": null,
"units": [
{
"generatorName": "Svartisen G1",
"componentId": 673021,
"timeSeries": null
},
{
"generatorName": "Svartisen G2",
"componentId": 673022,
"timeSeries": null
}
]
}
},
{
"hpsId": 10037,
"powerPlant": {
"name": "Stølsdal",
"id": 16605,
"regionId": 20,
"priceArea": 2,
"timeSeries": null,
"units": [
{
"generatorName": "Stølsdal G1",
"componentId": 166051,
"timeSeries": null
}
]
}
},
.....
使用这个我可以获得响应结构中的第 0 个元素:
hpsId = response.json()[0]["hpsId"]
但是我想将请求中的所有 hpsids 和所有 id 保存到“可能是列表或字典之类的东西?以便以后能够访问。
我猜想围绕响应运行的 for 循环与响应中的元素数量一样多,比如 1000,将该条件放入表达式中:
hpsId = response.json()[0-1000]["hpsId"]
我知道这是伪代码,但有什么想法吗?
现在的工作要求:
def test_get_powerplant():
global hpsId
global powerplantId
# Act:
response = get_requests(token, '/mfrr-eam/api/mfrr/eam/powerplant/all')
try:
hpsId = response.json()[0]["hpsId"] # Get the hpsId
print("HPS Ids: ", hpsId)
print(response.text)
except KeyError:
print("Unable to get hpsID")
try:
powerplantId = response.json()[0]["powerPlant"]["id"] # Get the powerplant id
print("PP Ids: ", powerplantId)
except KeyError:
print("Unable to get powerplantId")
# Assertion:
assert response.status_code == 200 # Validation of status code
只需使用
for
-循环
data = response.json()
all_hpsIds = []
all_powerplantIds = []
for item in data:
all_hpsIds.append(item["hpsId"])
all_powerplantIds.append(item["powerPlant"]["id"])
或
list comprehension
data = response.json()
all_hpsIds = [item["hpsId"] for item in data]
all_powerplantIds = [item["powerPlant"]["id"] for item in data]