如何使用python从json文件中打印特定值?

时间:2016-05-01 17:58:18

标签: python linux python-2.7

我是使用python的新手,我想知道如何使用python从我的json文件中打印一些值,以下是我的json文件

{
    "igt@gem_reloc_overflow@single-overflow": {
        "__type__": "TestResult",
        "command": "/home/gfx/intel-graphics/intel-gpu-tools/tests/gem_reloc_overflow --run-subtest single-overflow",
        "dmesg": "",
        "environment": "PIGLIT_PLATFORM=\"mixed_glx_egl\" PIGLIT_SOURCE_DIR=\"/home/gfx/intel-graphics/intel-gpu-tools/piglit\"",
        "err": "(gem_reloc_overflow:19562) CRITICAL: Test assertion failure function reloc_tests, file gem_reloc_overflow.c:260:\n(gem_reloc_overflow:19562) CRITICAL: Failed assertion: __gem_execbuf(fd, &execbuf) == -14\n(gem_reloc_overflow:19562) CRITICAL: error: -22 != -14\nSubtest single-overflow failed.\n**** DEBUG ****\n(gem_reloc_overflow:19562) DEBUG: relocation_count=4294967295\n(gem_reloc_overflow:19562) CRITICAL: Test assertion failure function reloc_tests, file gem_reloc_overflow.c:260:\n(gem_reloc_overflow:19562) CRITICAL: Failed assertion: __gem_execbuf(fd, &execbuf) == -14\n(gem_reloc_overflow:19562) CRITICAL: error: -22 != -14\n****  END  ****\n",
        "exception": null,
        "out": "IGT-Version: 1.14-g1e9a3ac (x86_64) (Linux: 4.6.0-rc4-drm-intel-nightly-ww17-commit-1e81bac+ x86_64)\nStack trace:\n  #0 [__igt_fail_assert+0x101]\n  #1 [reloc_tests+0x6d6]\n  #2 [<unknown>+0x6d6]\nSubtest single-overflow: FAIL (8.469s)\n",
        "pid": 19562,
        "result": "fail",
        "returncode": 99,
        "subtests": {
            "__type__": "Subtests"
        },
        "time": {
            "__type__": "TimeAttribute",
            "end": 1462072402.5360818,
            "start": 1462072393.7328644
        },
        "traceback": null
    }
}

我需要的值是“结果:失败”。

到目前为止,我有这段代码:

import json

with open("9.json") as json_file:
json_data = json.load(json_file)
print(json_data)

thaks

4 个答案:

答案 0 :(得分:1)

json.load函数返回一个字典(类型为dict的对象)。

字典将密钥与线索相关联。要访问字典中的值,可以使用以下语法:

value = dictionary[key]

在您的特定情况下:

result = json_data['result']

答案 1 :(得分:1)

给它一个机会!

for key, value in json_data.iteritems():
    result = value['result']

print result

更新(评论中的问题): 如果您有多个文件并希望一次存储所有信息 - 请尝试将其全部放入字典中。这取决于您想要密钥的内容。但试试这个(这将创建一个{json_key: result_value}

的dicitonary
all_results = {}
json_file_list = ['file_1.json', 'file_2.json']
for file in json_file_list:
    with open(file) as json_file:
        json_data = json.load(json_file)
        for key, value in json_data.iteritems():
            if 'result' in value:
                all_results[key] = value['result']
return all_results

答案 2 :(得分:0)

json_data["igt@gem_reloc_overflow@single-overflow"]["result"]

这将打印结果

答案 3 :(得分:0)

json数据存储为python字典。

因此您可以访问&#34;结果&#34;的值。如下:

json_data["igt@gem_reloc_overflow@single-overflow"]["result"]

W.R.T您的代码:

import json

with open("9.json") as json_file:
        json_data = json.load(json_file)


print(json_data["igt@gem_reloc_overflow@single-overflow"]["result"])