java - 使用 Groovy 集合精确匹配字符串格式
问题描述
我有一个关于使用 groovy 集合匹配确切字符串格式的问题。
def createPullRequest(projectSlug, repoSlug, title, description, sourceBranch, targetBranch) {
//this is reading in the array with the user names
def names = BitbutkcetUtil.getGroupUsers(teamName, activeOnly)
def prResponse = this.steps.httpRequest(
acceptType: 'APPLICATION_JSON',
authentication: this.userId,
contentType: 'APPLICATION_JSON',
httpMode: 'POST',
ignoreSslErrors: true,
quiet: true,
requestBody: """
{
"title": "${title}",
"description": "${description}",
"state": "OPEN",
"open": true,
"closed": false,
"fromRef": { "id": "${sourceBranch}" },
"toRef": { "id": "${targetBranch}" },
"locked": false,
"reviewers": [
//I want to replace this hardcoded names with the string values inside the array `names`
{ "user": { "name": "HardCoded1" } },
{ "user": { "name": "HardCoded2" } },
{ "user": { "name": "HardCoded3" } },
{ "user": { "name": "HardCoded4" } }
]
}
""",
responseHandle: 'STRING',
url: "https://bitbucket.absolute.com/rest/api/latest/projects/${projectSlug}/repos/${repoSlug}/pull-requests",
validResponseCodes: '200:299')
def pullRequest = this.steps.readJSON(text: prResponse.content)
prResponse.close()
return pullRequest['id']
}
我想要做的是我想用数组中的字符串元素替换其中的hardcoded
名称。我想使用该集合,但我必须匹配确切的格式 reviewers
names
{ "user": { "name": "HardCoded1" } },
{ "user": { "name": "HardCoded2" } },
{ "user": { "name": "HardCoded3" } },
{ "user": { "name": "HardCoded4" } }
现在,我有[reviewers: names.collect{ [user: [name: it]] }]
,它正在输出以下内容:
[reviewers:[[user:[name:name1]],
[user:[name:name2]],
[user:[name:name3]],
[user:[name:name4]]]]
我怎样才能使输出采用以下格式?
"reviewers": [
//I want to replace this hardcoded names with the string values inside the array `names`
{ "user": { "name": "HardCoded1" } },
{ "user": { "name": "HardCoded2" } },
{ "user": { "name": "HardCoded3" } },
{ "user": { "name": "HardCoded4" } }
]
任何帮助将不胜感激!
解决方案
您看到的是toString()
在地图元素列表上调用方法的结果。对于有效的 JSON 表示,您可以将collect()
方法的结果传递给 JsonOutput.toJSON()
. 像这样的东西:
requestBody: """
{
"title": "${title}",
"description": "${description}",
"state": "OPEN",
"open": true,
"closed": false,
"fromRef": { "id": "${sourceBranch}" },
"toRef": { "id": "${targetBranch}" },
"locked": false,
"reviewers": ${JsonOutput.toJson(names.collect{ [user: [name: it]] })}
}
"""
JsonOutput.toJSON()
第一次在 Jenkins Pipeline 中使用时可能需要脚本批准。
推荐阅读
- android - 在 Recyclerview 中比较旧数据和新数据
- python - How to apply Optimizer on Variable in Chainer?
- javascript - 从输入类型文件 javascript 下载文件
- json - 空手道删除 JSON 的不同部分
- php - PHP PDO未定义索引错误使用Fileuploader类
- python - 解析文本文件并从中创建 json
- powershell - 如何运行一次 Get-Credential,然后在同一会话中存储凭据并重用凭据
- javascript - 从父母传递给孩子的onChange函数不起作用
- python - Django Models - SQL 等效的多个表加入 DJANGO
- unit-testing - Junit5 模拟一个静态方法