Vikram Vikram - 4 months ago 13
JSON Question

How to extract values from json which has multiple hierarchies inside using Python

Below is the json content, how to extract values for "GBL_ACTIVE_CPU" using python.

{
"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"
}
]
]
}


I tried below code, but doesn't work. Any help is appreciated:

result = json.loads(jsonoutput)
print(result)
node = result["Metric Payload"]["Instances"]["GBL_ACTIVE_CPU"]
print(node)


I get below error:

TypeError: list indices must be integers or slices, not str

Answer

In JSON "Instances" is a list. You are accessing it like a dict. So it have 2 ways on is static other is dynamic.

If you like to use static way:-

result = json.loads(jsonoutput)
print(result)
node = result["Metric Payload"][0]["Instances"][0]["GBL_ACTIVE_CPU"]
print(node)

If you like to use dynamic way:-

result = json.loads(jsonoutput)
print(result)
for metric in result["Metric Payload"]: 
    for inst in metric["Instances"]:
        node = inst["GBL_ACTIVE_CPU"]
        print(node)