繁体   English   中英

如何使用 Python 从 Json 文件中读取嵌套列表信息

[英]how to read nested lists information from a Json file using Python

这是我的 Jason 文件的一部分,我想阅读“运行”->“结果”->“属性”下的“信息”

我正在尝试以下操作:

with open(inputFile, "r") as readFile:
    data = json.load(readFile)
    print(type(data))
    print("Run data type is: ",type(data['runs']))
    #print("properties data type is: ", type(data['runs']['properties']))
    # error:     print("results data type is: ", type(data['runs']['properties']))TypeError: list indices must be integers or slices, not str
    for info in data['runs']:
        res = info.get('results',{})
        #res = info.get('results', {}).get('properties', None)
        #Error: AttributeError: 'list' object has no attribute 'get'
        #inf = info.get('properties')
        print(res)

我评论的所有部分都不起作用。 我还添加了错误消息,我如何在循环中读取“信息”?

{
  "$schema" : "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.4.json",
  "version" : "2.1.0",
  "runs" : [ {
    "tool" : { ...},
    "artifacts" : [ ...],
    "results" : [ {
      "ruleId" : "DECL_MISMATCH",
      "ruleIndex" : 0,
      "message" : {
        "text" : "XXXXX"
      },
      "level" : "error",
      "baselineState" : "unchanged",
      "rank" : 100,
      "kind" : "fail",
      "properties" : {
        "tags" : [ "databaseId", "metaFamily", "family", "group", "information", "severity", "status", "comment", "justified", "assignedTo", "ticketKey", "color" ],
        "databaseId" : 54496,
        "metaFamily" : "Defect",
        "family" : "Defect",
        "group" : "Programming",
        "information" : "Impact: High",
        "severity" : "Unset",
        "status" : "Unreviewed",
        "comment" : "",
        "justified" : false,
        "color" : "RED"
      },
      "locations" : [ {
        "physicalLocation" : {
          "artifactLocation" : {
            "index" : 0
          }
        },
        "logicalLocations" : [ {
          "fullyQualifiedName" : "File Scope",
          "kind" : "function"
        } ]
      } ]
    } ]
  } ]
}

当您尝试访问列表中的关键properties时,您必须设置索引号。 在此json ,您发布的索引号可以是0 所以代码大概应该是这样的:

with open(inputFile, "r") as readFile:
    data = json.load(readFile)
    print(type(data))
    print("Run data type is: ",type(data['runs']))
    #print("properties data type is: ", type(data['runs']['properties']))
    # error:     print("results data type is: ", type(data['runs']['properties']))TypeError: list indices must be integers or slices, not str
    for info in data['runs']:
        # res = info.get('results',{})
        res = info.get('results', {})[0].get('properties', None)
        #inf = info.get('properties')
        print(res)
for run in data['runs']:
    for result in run['results']:
        properties = result['properties']
        print("information = {}".format(properties['information']))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM