Reputation: 589
How to replace the version from "1.0.2" to "2.6.5" in a json file "deploy.json" using groovy scripting, and the file content has been provided below.
{
"versions": [
{
"version": "1.0.2",
"conf": "replian"
},
{
"version": "1.0.2",
"conf": "hp"
},
{
"version": "1.0.2",
"conf": "shutoff"
},
{
"version": "1.0.2",
"conf": "spark"
}
]
}
I've tried the below, but getting an error;
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def content = """
{
"versions": [
{
"version": "1.0.2",
"conf": "replian"
},
{
"version": "1.0.2",
"conf": "hp"
},
{
"version": "1.0.2",
"conf": "shutoff"
},
{
"version": "1.0.2",
"conf": "spark"
}
]
}"""
def slurped = new JsonSlurper().parseText(content)
def builder = new JsonBuilder(slurped)
builder.content.versions.find{it.version}.version = "2.6.5"
println(builder.toPrettyString())
The issue is: Only first conf "replian" version is getting replaced when i use the above script;
{
"version": "2.6.5",
"conf": "replian"
},
{
"version": "1.0.2",
"conf": "hp"
},
{
"version": "1.0.2",
"conf": "shutoff"
},
{
"version": "1.0.2",
"conf": "spark"
}
Upvotes: 0
Views: 452
Reputation: 4998
Use collect method
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def content = """
{
"versions": [
{
"version": "1.0.2",
"conf": "replian"
},
{
"version": "1.0.2",
"conf": "hp"
},
{
"version": "1.0.2",
"conf": "shutoff"
},
{
"version": "1.0.2",
"conf": "spark"
}
]
}"""
def slurped = new JsonSlurper().parseText(content)
def builder = new JsonBuilder(slurped)
builder.content.versions.collect{ it.version = '2.6.5' }
println(builder.toPrettyString())
Output
{
"versions": [
{
"version": "2.6.5",
"conf": "replian"
},
{
"version": "2.6.5",
"conf": "hp"
},
{
"version": "2.6.5",
"conf": "shutoff"
},
{
"version": "2.6.5",
"conf": "spark"
}
]
}
Upvotes: 1