我正在使用 Pytest 进行 HTTP API 调用,并希望获取给定字母名称的值。 响应如下所示:
[
{
"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
}
]
}
}
]
我想在上面的响应中获取generatorName Stølsdal G1的componentId的属性值(166051)并保存该值。
但是,鉴于我在发出请求之前只知道生成器的名称,我该如何搜索它?
我当时是这样想的:
componentId= response.json()[what to put here?]["hpsId"]["componentId"]
当您将 JSON 数据转换为可以在 Python 中使用的数据时,您将获得一个字典列表。
没有捷径解决方案。您只需浏览结构即可。
例如:
import json
data = '''[
{
"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
}
]
}
}
]'''
def getComponentId(generatorName, jdata):
for d in jdata:
for unit in d["powerPlant"]["units"]:
if unit["generatorName"] == generatorName:
return unit["componentId"]
print(getComponentId("Stølsdal G1", json.loads(data)))
输出:
166051