簡體   English   中英

如何使用Python從內部具有多個層次結構的json提取值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM