简体   繁体   中英

Parsing JSON object in Groovy

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("/")]​​​)​

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM