1

如何编写一些 groovy 脚本来返回按嵌套在键中的键name排序的名称数组 () ?created_atcommit

使用作为样本数据:

[
{"name":"v10.8.0-rc13",
"message":"Version v10.8.0-rc13",
"target":"171b50a40984c358a07c7e37ee95f8d788718198",
"commit":
 {
 "id":"1b3911c3cc8e72cc93370a90a597e2a0b944bcc2",
 "short_id":"1b3911c3",
 "title":"Update VERSION to 10.8.0-rc13",
 "created_at":"2018-05-18T12:43:58.000+01:00",       <------ I WANT TO SORT BY THIS 
 "parent_ids":["a7090d00098a4acc03cfc2b01df8019c918bd0bc"],
 "message":"Update VERSION to 10.8.0-rc13\n",
 "author_name":"Filipa Lacerda",
 "author_email":"filipa@gitlab.com",
 "authored_date":"2018-05-18T12:43:58.000+01:00",
 "committer_name":"Filipa Lacerda",
 "committer_email":"filipa@gitlab.com",
 "committed_date":"2018-05-18T12:43:58.000+01:00"
  },
"release":null
},
.
.
.
]

到目前为止,我正在使用这样的东西来获取未排序的名称列表:

List<String> tags= new ArrayList<String>()

def url="curl -X GET http://blah_blah"
def payload = url.execute().text
def slurper = new JsonSlurper()
def response = slurper.parseText(payload)

for(item in response)
{
   tags.add(item.name)
}

println(tags)

在这种情况下,response是类型java.util.ArrayList

并且response[0]是类型groovy.json.internal.LazyMap

到目前为止,我发现的所有示例都使用.sortor.SortBy方法在LazyMap. **更新**我不认为这是一个真实的陈述。

4

1 回答 1

3

要从这种结构中获取标签名称列表,可以使用 Groovy 的扩展运算符:

def tags = response*.name

可以简化为:

def tags = response.name

这相当于:

def tags = response.collect { it.name }

现在,如果您希望此列表按键排序,您可以在使用扩展运算符之前commit.created_at调用方法,例如.sort {}

def tags = response.sort { it.commit.created_at }.name

它将按升序对名称列表进行排序。如果您对降序感兴趣,那么您可以否定 sort 方法的主体:

def tags = response.sort { !it.commit.created_at }.name

您可以在下面找到一个完整的示例:

import groovy.json.JsonSlurper

def json = "https://gitlab.com/api/v4/projects/gitlab-org%2Fgitlab-ce/repository/tags".toURL().text

def response = new JsonSlurper().parseText(json)

def tags = response.sort { it.commit.created_at }.name

println tags

输出:

[v10.7.0, v10.8.0.pre, v10.7.1, v10.5.8, v10.6.5, v10.7.2, v10.8.0-rc1, v10.7.3, v10.8.0-rc2, v10.8.0-rc3, v10.8.0-rc4, v10.8.0-rc6, v10.8.0-rc5, v10.8.0-rc7, v10.8.0-rc8, v10.8.0-rc9, v10.8.0-rc10, v10.8.0-rc11, v10.8.0-rc12, v10.8.0-rc13]

希望能帮助到你。

于 2018-05-18T18:40:06.800 回答