如何解析具有json的文本文件并获取数组元素

问题描述

我正在尝试使用json解析文本文件,并从jsonArray中获取元素之一。下面是我要解析的json

[
  {
    "ContainerConfig": {
      "Labels": {
        "commit-id": "abcdef123d","author": "Jon"
      }
    }
  }
]

下面是我在jenkinsfile中的常规实现

def jsonStr=readFile('temp.txt').trim()
//here temp.txt consist of above json 

JsonSlurper slurper = new JsonSlurper()
def parsedJson=slurper.parseText(jsonStr)

def commitId=parsedJson[0].ContainerConfig.Labels.commit-id

我收到此错误消息-

java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.EchoStep.message expects class java.lang.String but received class java.util.ArrayList 

        

解决方法

使用JsonSlurper并不是真正的最佳实践,它会导致CPS出现问题,请改用readJSON(也更容易使用IMO)。

我还怀疑-中的commit-id会导致错误,您应该改用["commit-id"] snytax。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...