groovy 使用闭包遍历JSON数组

9fkzdhlc  于 3个月前  发布在  其他
关注(0)|答案(1)|浏览(70)

在Groovy中(特别是在Jenkins中),我使用readJSON方法从文件中读取了一个JSON数组。
看起来像这样:

[
  {
    "name": "bob",
    "age": "36"
  },
  {
    "name": "wizard",
    "age": "420"
  }
]

字符串
我想用一个类似withEachIndex的闭包遍历每个数组索引。当我运行这样的代码时:

array.withEachIndex { it, i ->
  println it.name
  println it.age
  println "Index: ${i}"
}


Jenkins哽咽道:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: net.sf.json.JSONArray.withEachIndex() is applicable for argument types: (org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [org.jenkinsci.plugins.workflow.cps.CpsClosure2@f048bab]


我尝试过将数组转换为Java数组(通过调用.toArray()),并将其转换为集合(通过调用.toCollection()),但这些都没有闭包方法。
如何将这个对象转换为一个数组,以便在Groovy中使用闭包方法?

d8tt03nd

d8tt03nd1#

我想你正在寻找这个eachWithIndex

def arr = [
  [
    "name": "bob",
    "age": "36"
  ],
  [
    "name": "wizard",
    "age": "420"
  ]
]
arr.eachWithIndex { n, i -> println( "${i}: ${n.name} ${n.age}") }

字符串

相关问题