打印特定JSON键的所有出现次数

2024-09-29 21:57:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python打印JSON字符串中每个事件的值。你知道吗

这是我的JSON:

{
    "changed": false,
    "results": [{
            "arch": "x86_64",
            "epoch": "0",
            "name": "nagios-plugins-check_ansible",
            "nevra": "0:nagios-plugins-check_ansible-20170803-4.1.x86_64",
            "release": "4.1",
            "repo": "nagios_plugins",
            "version": "20170803",
            "yumstate": "available"
        },
        {
            "arch": "x86_64",
            "epoch": "0",
            "name": "nagios-plugins-check_memory",
            "nevra": "0:nagios-plugins-check_memory-20170801-19.1.x86_64",
            "release": "19.1",
            "repo": "nagios_plugins",
            "version": "20170801",
            "yumstate": "available"
        },
        {
            "arch": "x86_64",
            "epoch": "0",
            "name": "nagios-plugins-check_radius",
            "nevra": "0:nagios-plugins-check_radius-20170802-3.1.x86_64",
            "release": "3.1",
            "repo": "nagios_plugins",
            "version": "20170802",
            "yumstate": "available"
        }
    ]
}

我想把每次出现的“nevra”键打印到控制台上。我试过:

import json, sys

obj=json.load(sys.stdin)

i = 0
while True:
    try:
        print(obj["results"][i]["nevra"])
        i = (i + 1)
    except IndexError:
        exit(0)

但这会产生:

NameError: name 'false' is not defined

Tags: namejsonfalsereleaseversioncheckpluginsrepo
3条回答

简单使用:

for result in obj['results']:
    print(result['nevra'])

这会产生:

>>> for result in obj['results']:
...     print(result['nevra'])
... 
0:nagios-plugins-check_ansible-20170803-4.1.x86_64
0:nagios-plugins-check_memory-20170801-19.1.x86_64
0:nagios-plugins-check_radius-20170802-3.1.x86_64

to print every occurence of the "nevra" key to the console

发现jq工具:

jq -r '.results[] | if has("nevra") then .nevra else empty end' yourjsonfile

输出:

0:nagios-plugins-check_ansible-20170803-4.1.x86_64
0:nagios-plugins-check_memory-20170801-19.1.x86_64
0:nagios-plugins-check_radius-20170802-3.1.x86_64

你也可以完成一行:

nevra = [ v["nevra"] for v in data['results']]

输出:

['0:nagios-plugins-check_ansible-20170803-4.1.x86_64', '0:nagios-plugins-check_memory-20170801-19.1.x86_64', '0:nagios-plugins-check_radius-20170802-3.1.x86_64']

相关问题 更多 >

    热门问题