I am making an HTTP API call using Pytest and want to obtain a value given a name in letters.
The response looks like this:
[
{
"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
}
]
}
}
]
I want ot get the attribute value (166051) for componentId for generatorName Stølsdal G1 in the above response and save the value.
But how can I search for this given I only know the name of the generator before the request is being made?
I was thinking like this:
componentId= response.json()[what to put here?]["hpsId"]["componentId"]
2
Answers
When you convert the JSON data to something that you can use in Python, you will have a list of dictionaries.
There’s no shortcut solution. You just have to navigate through the structure.
For example:
Output:
Note:
Returns None if the given search criterion cannot be found