如何使用python解决获取json数据的问题



我在python编程中很新,所以我创建了下面的python脚本,以便在包含3000个或更多json文件的文件夹中进行迭代,我不知道如何在这3000个json文件中进行迭代以避免手动放在脚本中,我需要在json文件所在的位置放一个特定的路径,我也不知道如何声明它。

import json
all_results = {}
json_file_list = ['1.json', '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

在运行我的python脚本后,我出现了以下错误:

File "getResult.py", line 20
  return all_results
SyntaxError: 'return' outside function

这就是我的jsons文件

{"igt@gem_reloc_overflow@单个溢出":{"类型":"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/piggit \","err":"(gem_reloc_overflow:19562)关键:测试断言失败函数relocat_tests,文件gem_reloc_overflow。c:260:\n \n(gem_reloc_overflow:19562)关键:测试断言失败函数reloca_tests,文件gem_reloc_overflow。c:260:\n-14\n***结束***","exception":null,"out":"IGT版本:1.14-g1e9a3ac(x86_64)(Linux:4.6.0-rc4-drm-intel-dnightly-ww17-commit-1e81bac+x86_64)\n堆栈跟踪:\n#0[__IGT_fail_assert+0x101]\n#1[reloca_tests+0x6d]\n#2[+0x6d6]\n最小单个溢出:fail(8.469s)\n","pid":19562,"结果":"失败","returncode":99,"子测验":{"__type":"子测试"},"时间":{"类型":"TimeAttribute","结束":1462072402.5360818,"启动":1462072393.7328644},"回溯":null}}

欢迎任何帮助,感谢

也许您想要print all_results而不是return all_results。或者你可以在找到它们时一个接一个地打印出来。

要迭代目录中的文件而不必手动输入文件名,可以使用os.walk()os.listdir()。有关详细信息,请参阅此问题。

语法错误似乎不言自明。您有一个不在函数定义内部的return语句;这是无效的Python。如果要输出结果,请使用print

将JSON文件目录的路径存储到变量

mypath = "/home/json_file_directory"

使用os.listdir()列出所有json文件。

一旦有了json文件名,就使用

 os.path.join(mypath,filename) #to get the exact path of file.

最新更新