我要解析一个JSON文件来获取特定的信息。下面是JSON:
{
"$schema" : "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.4.json",
"version" : "2.1.0",
"runs" : [ {
"tool" : {
"driver" : {
"name" : "xxx ",
"semanticVersion" : "ccc",
"organization" : "www",
"rules" : [ {
"id" : "MISRA C++:2008 18-0-1",
"name" : "18-0-1 The C library shall not be used."
}, {
"id" : "MISRA C++:2008 3-9-2",
"name" : "3-9-2 Typedefs that indicate size and signedness should be used in place of the basic numerical types."
}, {
"id" : "MISRA C++:2008 0-1-2",
"name" : "0-1-2 A project shall not contain infeasible paths."
}, {
"id" : "MISRA C++:2008 5-0-13",
"name" : "5-0-13 The condition of an if-statement and the condition of an iteration-statement shall have type bool."
}, {
"id" : "MISRA C++:2008 5-2-4",
"name" : "5-2-4 C-style casts (other than void casts) and functional notation casts (other than explicit constructor calls) shall not be used."
}, {
"id" : "MISRA C++:2008 7-1-1",
"name" : "7-1-1 A variable which is not modified shall be const qualified."
}, {
"id" : "MISRA C++:2008 15-5-3",
"name" : "15-5-3 The terminate() function shall not be called implicitly."
}, {
"id" : "MISRA C++:2008 15-3-2",
"name" : "15-3-2 There should be at least one exception handler to catch all otherwise unhandled exceptions"
} ]
}
},
}
}
我想要一个简单的python列表,其中包含所有ids
及其在rules
中的值。预期产出实例:
["MISRA C++:2008 18-0-1", "MISRA C++:2008 3-9-2", "MISRA C++:2008 0-1-2", "MISRA C++:2008 5-0-13", "MISRA C++:2008 5-2-4", "MISRA C++:2008 7-1-1", MISRA C++:2008 15-5-3", "MISRA C++:2008 15-3-2"]
我怎样才能得到这些信息?
我试过的..。我正试图像下面这样在结构中导航,但失败了。
with open(json_file, 'r') as fcc_file:
fcc_data = json.load(fcc_file)
for channel in fcc_data:
print(fcc_data[channel]["tool"])
错误:
TypeError: string indices must be integers
发布于 2022-07-06 20:04:34
您需要遍历runs
和rules
中的嵌套列表。
您可以使用嵌套列表理解来获得所需的结果。
result = [rule['id'] for run in fcc_data['runs'] for rule in run['tool']['driver']['rules']]
发布于 2022-07-06 20:03:01
你搞砸了输入结构。
with open(json_file, 'r') as fcc_file:
fcc_data = json.load(fcc_file)
for channel in fcc_data['runs']: # iterating over a list now
print([r['id'] for r in channel['tool']['driver']['rules']])
https://stackoverflow.com/questions/72889196
复制相似问题