在JenkinsFile中合并一个JSON列表和一个JSON数组

huangapple go评论59阅读模式
英文:

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:

&gt;[&quot;[Account:1, Key:CI, Value:SERVICES]&quot;, &quot;[Account:2, Key:CI, Value:]&quot;]

https://onecompiler.com/groovy/3zddfxgan

We simply loop through the array, convert each item to a json map object, append the new &quot;Account&quot; key into the map with the corresponding value of the other list, and replace the original array item with the modified map value.

</details>



huangapple
  • 本文由 发表于 2023年7月3日 12:25:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定