![](/img/trans.png)
[英]How to extract information from multiple XML nodes and hierarchies using python?
[英]How to extract values from json which has multiple hierarchies inside using Python
以下是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 ”是一个列表。 您像字典一样访问它。 因此它有2种方式是静态的,另一种是动态的。
如果您想使用静态方式:-
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.