I hava a large json response on an api call using pytest. I want to pick up all hpsIds and all ids and "store it somewhere" to be used as parameters in a subsequent request.
[
{
"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
}
]
}
},
.....
Using this I can obtain the 0th element in the response structure:
hpsId = response.json()[0]["hpsId"]
But I want to get al the hpsids and all the ids in the request saved to "something as maybe a list og dict? to be able to access later.
I guess a for-loop around the response running for as many elements there is in the response, say 1000, putting that condition in the expression:
hpsId = response.json()[0-1000]["hpsId"]
I know this is pseudo-code but any ideas?
working request now:
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
2
Answers
Simply use
for
-loopor
list comprehension
You could also keep values as pairs:
or as dictionary
If you want to save all hpsId and id into lists: