I have a json and its response is {"canMerge":false,"conflicted":true,"outcome":"CONFLICTED","vetoes":[{"summaryMessage":"Requires approvals","detailedMessage":"You need 2 more approvals before this pull request can be merged."}]}
and I want to filter out data on the basis of "outcome":"CONFLICTED" for this I have tried following ways-
def mergeResponse = readJSON file:mergeFileName
for(mergenew in mergeResponse.values)
{
if(mergenew.outcome == "CONFLICTED") {
echo "pull request can not merged"
}
when I am trying above it is skipping if loop directly eventhough condition match properly I am not getting why?
ALSO TRIED BELOW
import groovy.json.JsonSlurper
def slurper = new JsonSlurper().parseText(mergenew)
assert slurper.outcome == "CONFLICTED"
String id = mergenew.getString("id");
echo "pull request can not merged"
getting error for above is
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: groovy.json.JsonSlurper.parseFile() is applicable for argument types: (org.apache.commons.collections.map.ListOrderedMap$ListOrderedMapEntry) values: [canMerge=false]
Possible solutions: parse([B), parse([C), parse(java.io.File), parse(java.io.InputStream), parse(java.io.Reader), parse(java.net.URL)
I also approved script in jenkins script approval for JsonSlurper.parseText
Please help me. Any help is appreciated.
try this : (set the file name var to whatever the file is)
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
data = jsonSlurper.parse(new File(mergeFileName))
assert data.outcome == "CONFLICTED"
println("pull request can not merged")
You can use Pipeline Utility Steps to read a json file. This works for me:
def data = readJSON file: "${WORKSPACE}/data.json" // here just read the json file
def outcome = "${data.outcome}"
if(outcome == "CONFLICTED") {
echo "pull request can not merged"
}
Related
I created a method as shown online:
#NonCPS
def parseJsonString(String jsonString) {
def lazyMap = new JsonSlurper().parseText(jsonString)
// JsonSlurper returns a non-serializable LazyMap, so copy it into a regular map before returning
def m = [:]
m.putAll(lazyMap)
return m
}
But I get the following error:
ERROR: java.io.NotSerializableException: groovy.json.internal.LazyMap
To work around this, I have to create an entire method to perform an entire step. For instance, in a method, I would do the same as above, parse the information I want, and finally return it as a string.
This, however, presents another issue, especially if you wrap this method inside a withCredentials, which would then require another withCredentials.
I finally find a BETTER solution!
readJSON() method from the Jenkins "Pipeline Utility Steps" plugin as shown here:
https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace
Here is a sample where we can finally ditch that ugly GROOVY JSONPARSE crap.
node() {
stage("checkout") {
def jsonString = '{"name":"katone","age":5}'
def jsonObj = readJSON text: jsonString
assert jsonObj['name'] == 'katone' // this is a comparison. It returns true
sh "echo ${jsonObj.name}" // prints out katone
sh "echo ${jsonObj.age}" // prints out 5
}
}
Im Trying to write a Groovy script which performs a REST api call and gets an JSON object, then, i need to get a specific string out of this JSON and check if it matches another string that i provides in the script.
i did everything until the section of comparison,
the string that im getting from the JSON looks like
[AAAAAA/BBBBBB/CCCCCC/file.txt]
and this is my Groovy script:
/*Import Section*/
//--------------//
groovy.json.*
/*Var Declaration*/
//---------------//
String errMessage = "There were no Junit tests impacted in this PR,
Comparison is: "
String scssMessage = "There were Junit tests impacted in this PR,
Comparison is: "
usr= "USERNAME"
pass= "PASSWORD"
pr_num = 92
String validPath = "AAAAAA/BBBBBB/CCCCCC/DDDDDD/EEEEEE"
def copmarison = !false
/*REST API call*/
//------------//
url= "http://{$usr}:
{$pass}#XX.XXX.X.XX:PPPP/rest/api/1.0/projects/XX/repos/TTTTT/pull-
requests/+{$pr_num}/changes?changescope"
process = [ 'bash', '-c', "curl ${url}" ].execute()
process.waitFor()
/*JSON parsing*/
//------------//
def info = new JsonSlurper().parseText(process.text)
def path = info.values.path.toString
/*Impacted JUNIT verifycation*/
//---------------------------//
if(path==validPath){
println ("$scssMessage"+"Valid"+"\n")
comparison=true
}else{
println ("$errMessage"+"Not Valid"+"\n")
comparison=!false
}
Im sure that my comparison isnt good and im looking to compare and find
if part of my "path" contained in my "validPath".
for example, the following case means true:
AAAAAA/BBBBBB/CCCCCC/file.txt
contained in:
AAAAAA/BBBBBB/CCCCCC/DDDDDD/EEEEEE
and i need to find a way to make this comparison
please help
If I understand your question correctly, all you need to check is the path part of your file against a specific path. In that case, this will work:
// you should already have these; including here for clarity
def file = "AAAAAA/BBBBBB/CCCCCC/file.txt"
def path = "AAAAAA/BBBBBB/CCCCCC/DDDDDD/EEEEEE"
return path.contains(file[0..file.lastIndexOf("/")])
How to parse json response using groovy script.
I am using SOAP UI and have json response as below-
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
Can anyone please share sample code to parse json object and post that some basic assertions check.
Thanks
Add a Script Assertion for the rest request test step with below script.
Define your expected data as shown in the snippet below as needed
It compares each key value with expected data.
JsonSlurper can be used to parse the response.
//Check if the response is not empty
assert context.response, 'Response is empty or null'
//Define expected data
def expectedData = [name: 'aaaaaaaaaaa', emailid: 'bbbbbbbbb']
def json = new groovy.json.JsonSlurper().parseText(context.response)
//Checks all elements of resource one by one and compare with expectedData
json.resource.each {k, v -> assert v == expectedData."$k" }
I am getting below json response:
{"participantUID": "000000000004871"}
I want to do assertion on participantUID.
My code:
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
assert jsonSlurper.participantUID == expectedparticipant
but I am getting error: groovy.lang.MissingPropertyException: No such property:
Please help me out. thanks
I'm not completely sure since you don't copy the complete MissingPropertyExceptionMessage in your question but since you're accessing correctly the response content using messageExchange context variable the problem is probably that you're not defining the expectedparticipant in your Script assertion try with:
def ResponseMessage = messageExchange.response.responseContent
def expectedparticipant = '000000000004871'
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
assert jsonSlurper.participantUID == expectedparticipant
I am using groovy to automate some tests on SoapUI, and I wanted to also automate assertions in a way I would get a field's name and value from a *.txt file and check if the wanted field does exist with the wanted value in the SOapUI response.
Suppose I have the following json response:
{
"path" : {
"field" : "My Wanted Value"
}
}
And from my text file I would have the following two strings :
path="path.field"
value="My Wanted Value"
I tried the following :
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response
assert json.path==value;
But of course it doesn't work.
Any idea how can I get it done please?
Thank you
I think your problem is to access a json value from a path based with . notation, in your case path.field to solve this you can use the follow approach:
import groovy.json.JsonSlurper
def path='path.field'
def value='My Wanted Value'
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step to
// find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Additionally I'm not sure if you're also asking how to read the values from a file, if it's also a requirement you can use ConfigSlurper to do so supposing you've a file called myProps.txt with your content:
path="path.field"
value="My Wanted Value"
You can access it using the follow approach:
import groovy.util.ConfigSlurper
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
println config.path // path.field
println config.value // My Wanted Value
All together (json path + read config from file):
import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper
def response = '''{
"path" : {
"field" : "My Wanted Value"
}
}'''
// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value
def json = new JsonSlurper().parseText response
// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
json = json[it]
}
assert json == value
println json // My Wanted Value
println value // My Wanted Value
Hope this helps,