首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用多层嵌套来解析JSON?

如何使用多层嵌套来解析JSON?
EN

Stack Overflow用户
提问于 2022-07-06 19:56:22
回答 2查看 45关注 0票数 0

我要解析一个JSON文件来获取特定的信息。下面是JSON:

代码语言:javascript
运行
复制
{
  "$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中的值。预期产出实例:

代码语言:javascript
运行
复制
["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"]

我怎样才能得到这些信息?

我试过的..。我正试图像下面这样在结构中导航,但失败了。

代码语言:javascript
运行
复制
with open(json_file, 'r') as fcc_file:
    fcc_data = json.load(fcc_file)
for channel in fcc_data:
    print(fcc_data[channel]["tool"])

错误:

代码语言:javascript
运行
复制
TypeError: string indices must be integers
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-06 20:04:34

您需要遍历runsrules中的嵌套列表。

您可以使用嵌套列表理解来获得所需的结果。

代码语言:javascript
运行
复制
result = [rule['id'] for run in fcc_data['runs'] for rule in run['tool']['driver']['rules']]
票数 3
EN

Stack Overflow用户

发布于 2022-07-06 20:03:01

你搞砸了输入结构。

代码语言:javascript
运行
复制
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']])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72889196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档