python - 如何使用Python从内部具有多个层次结构的json中提取值

标签 python json extract

下面是 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/

相关文章:

linux - 如何创建 tar 文件以便将文件放置在 tar.gz 文件的根文件夹中

c# - 如何以编程方式从 YouTube 视频中提取音频?

python - Pytorch:定义自定义函数

python - 如何使用 matplotlib 创建某种类型的网格

Python pickle/unpickle 到/从文件中提取列表

python - 在 Python 中识别一维和二维数据中的异常值 block

java - Android 中无标签字符串的 JSON 解析

jQuery + JSONP 返回数据为空?

ruby - 为什么我可以从 JSONB 值更新 PostgreSQL 列字符串而不是 Sequel 中的整数?

Python如何提取pandas数据框中[]括号内的指定字符串并使用 bool 值创建一个新列