英文:
Merge a list and an array of JSON in JenkinsFile
问题
我有一个看起来像这样的列表 -
[1,2,3,4,5,6]
我有一个JSON对象数组,看起来像这样 -
Full List: [{
"Key": "CI",
"Value": "SERVICES"
}
, {
"Key": "CI",
"Value": ""
}]
期望的输出 -
Full List: [{
"Key": "CI",
"Value": "SERVICES",
"Account": "1"
}
, {
"Key": "CI",
"Value": "",
"Account": "2"
}]
如何在Jenkins文件中使用Groovy实现这个?我已经尝试过但失败了。
英文:
I have a list that looks like this -
[1,2,3,4,5,6]
I have an array of JSON objects that looks like this -
Full List: [{
"Key": "CI",
"Value": "SERVICES"
}
, {
"Key": "CI",
"Value": ""
}]
Expected output -
Full List: [{
"Key": "CI",
"Value": "SERVICES",
"Account": "1"
}
, {
"Key": "CI",
"Value": "",
"Account": "2"
}]
How to do this inside jenkins file using groovy. I have tried and failed.
答案1
得分: 0
这将帮助你入门:
def list = [1,2,3]
def full_list = [{'Key': 'CI', 'Value': 'SERVICES'}, {'Key': 'CI', 'Value': ''}]
full_list.eachWithIndex { item, index ->
def json = new groovy.json.JsonSlurper().parseText(item)
json['Account'] = list[index]
full_list[index] = json
}
输出:
[{'Account': 1, 'Key': 'CI', 'Value': 'SERVICES'}, {'Account': 2, 'Key': 'CI', 'Value': ''}]
我们简单地循环遍历数组,将每个项转换为 JSON 映射对象,将新的 "Account" 键附加到映射中,其值来自另一个列表,然后用修改后的映射值替换原始数组项。
<details>
<summary>英文:</summary>
This should get you started:
def list = [1,2,3]
def full_list = ['{ "Key": "CI", "Value": "SERVICES" }' , '{ "Key": "CI", "Value": "" }']
full_list.eachWithIndex { item, index ->
def json = new groovy.json.JsonSlurper().parseText(item)
json["Account"] = list[index]
full_list[index] = json
}
Output:
>["[Account:1, Key:CI, Value:SERVICES]", "[Account:2, Key:CI, Value:]"]
https://onecompiler.com/groovy/3zddfxgan
We simply loop through the array, convert each item to a json map object, append the new "Account" key into the map with the corresponding value of the other list, and replace the original array item with the modified map value.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论