打印特定JSON密钥的每个出现

时间:2017-08-03 13:47:51

标签: python json python-2.7

我想用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

3 个答案:

答案 0 :(得分:4)

只需使用:

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

答案 1 :(得分:1)

你也可以完成一行:

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']

答案 2 :(得分:0)

  

将“nevra”键的每次出现都打印到控制台

发现 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