2016-05-01 39 views
1

即时通讯新使用python,我想知道我怎样才能从我的JSON文件使用python打印一些值,下面是我的JSON文件如何使用python从json文件打印特定值?

{ 
    "[email protected][email protected]": { 
     "__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

+0

的可能的复制(HT [从JSON响应的Python提取单个值] tp://stackoverflow.com/questions/12788217/extract-single-value-from-json-response-python) – flyingmeatball

+0

为什么这个问题带有linux标签? –

回答

1

给这个一杆!

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

print result 

UPDATE(在评论的问题): 如果有多个文件,并想存储的所有信息的一次 - 尝试都扔到字典。这可以根据你想要的键而变化。不过,试试这个(这将创建的{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 
+0

感谢它为我工作,我不知道我是否可以要求更多的一件事,但如果有可能有一些方法来改善这个脚本,我的意思是我有一个文件夹中的100个jsons,每个具有不同的结果,它是可能迭代他们和存储他们的不同结果在几个变量?结果将是:失败,通过,dmesg-warn,dmesg-fail,跳过,不完整。如果这是不可能的,我会明白谢谢 – shaveax

+0

@shaveax看到更新! – tknickman

+0

谢谢@tknickman,它适用于我:) – shaveax

1

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

字典将密钥与线索关联。要访问的字典里面的值,你可以使用这个语法:

value = dictionary[key] 

你的具体情况:

result = json_data['result']