下面是 json 内容,如何使用 python 提取“GBL_ACTIVE_CPU”的值。
{
"test": "00.00.004",
"Metric Payload": [
{
"ClassName": "test",
"SystemId": "test",
"uri": "http://test/testmet",
"MetaData": [
{
"FieldName": "GBL_ACTIVE_CPU",
"DataType": "STRING",
"Label": "test",
"Unit": "string"
}
],
"Instances": [
{
"InstanceNo": "0",
"GBL_ACTIVE_CPU": "4"
}
]
]
}
我试过下面的代码,但没有用。任何帮助表示赞赏:
result = json.loads(jsonoutput)
print(result)
node = result["Metric Payload"]["Instances"]["GBL_ACTIVE_CPU"]
print(node)
我得到以下错误:
TypeError: list indices must be integers or slices, not str
最佳答案
在 JSON 中,“Instances”是一个列表。您正在像听写一样访问它。所以它有两种方式,一种是静态的,另一种是动态的。
如果你喜欢使用静态方式:-
result = json.loads(jsonoutput)
print(result)
node = result["Metric Payload"][0]["Instances"][0]["GBL_ACTIVE_CPU"]
print(node)
如果你喜欢使用动态方式:-
result = json.loads(jsonoutput)
print(result)
for metric in result["Metric Payload"]:
for inst in metric["Instances"]:
node = inst["GBL_ACTIVE_CPU"]
print(node)
关于python - 如何使用Python从内部具有多个层次结构的json中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479152/