1

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
1
  • Remove the stray brace on line 4. Commented Jul 20, 2016 at 11:30

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for poiinting it out. Below one worked: node = result["Metric Payload"][0]["Instances"][0]["GBL_SYSTEM_ID"] Here, observe [0] after [Metric Payload]. Without this, it doesn't work. I believe, as Metric payload also is a list we need to have the index for it as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.