Forum Discussion

nkpalli's avatar
nkpalli
Contributor
8 years ago

Groovy script, handle hyphen

Hello team,

 

 

Working on groovy script to compare Json response format to SQL script values . created a hashmap object and when trying to loop through the reponse object based on a attribute which has 'hyphen' in the name attribute it gave missingproperty exception . I have tried handling this using string notation but now it complain with missing method exception  in this line (if (singleNode("lab-term") == dbproperty.lab_term(i)) )

 

Any  help is appreciated 

 

Here below is  Json response : In this example notice  "Lab-term" Key has a '-' hyphen in the  lab-term key . 

{
"data": [
{
"rentincrease": 290,
"effectiveprice": 1305,
"lab-term": 1,
}

}

 

Here below is groovy script :

 

import groovy.json.JsonSlurper
import groovy.xml.XmlUtil
import groovy.sql.Sql


// Get Project level attributes

def dbServer = context.expand( '${#Project#DatabaseServer}' )
def dbport = context.expand( '${#Project#port}' )
def dbInstance = context.expand( '${#Project#DatabaseInstance}' )
def dbname = context.expand( '${#Project#DatabaseName}' )
def dbbid = context.expand( '${#Project#bid}' )
def dbuid = context.expand( '${#Project#uid}' )
def dblabid = context.expand( '${#Project#labid}' )
//sql = Sql.newInstance("jdbc:sqlserver://$dbServer:$dbport;instanceName=$dbInstance;databaseName=$dbname;integratedSecurity=true")
sql = Sql.newInstance("jdbc:sqlserver://$dbServer:$dbport;instanceName=$dbInstance;databaseName=$dbname;integratedSecurity=true")


//Exesute API call using testrunner varibale
def prj = testRunner.testCase.testSuite.project.workspace.getProjectByName("LabTerms")
tCase = prj.testSuites['LabTerms'].testCases['GetLabTerms']
tStep = tCase.getTestStepByName("Validate LabTerms")
def runner = tStep.run(testRunner, context)
log.info ("runner status ....... : " + runner.hasResponse())

// Using Json Slurper class method

def Response = context.expand( '${Validate LabTerms#Response#$.data}' )//creating instance of slurperclass
log.info(Response)
def slurperResponse = new JsonSlurper().parseText(Response)
//log.info(Response)
def nodes = Response
def check = true
def singleNode = true
def mapRESPtoDB = [
"dollar-increase": "dollarincrease",
"effectiveprice": "effectiverent",
"lab-term": "lab_term",

]
// Query the db to get all labterms
def dbproperty = sql.rows("""
SELECT
rentincrease as rentincrease
effectiveprice as effectiveprice
lab_term as lab_term
FROM XYZ

where  rl.bid = $dbbid
and r1.uid = $dbuid
and rl.labID = $dblabid
""")
log.info(dbproperty)

//Compare API response to SQL query results

for (i = 1; i < nodes.size(); i++) {
singleNode = nodes[i]
log.info("i= " + i)
//log.info ("Iterating :API response: " + singleNode.lab-term + "SQL: " + dbproperty.lab_term[i])
if (singleNode("lab-term") == dbproperty.lab_term(i))
{
singleNode.each { at ->
log.info('API key/value: ' + at.key + ' ' + at.value)
log.info('DB:'+ at.key + dbproperty."${mapRESPtoDB.get(at.key)}"[i])
if (at.value == dbproperty."${mapRESPtoDB.get(at.key)}"[i]) {
check = true
} else {
check = false
log.info(at)
return
}
}
if(check == false) {
break
}
}else{
log.info('Does not meet criteria for compare ', singleNode(i))
}
if (check == false)
break
}
// Compare the API
if (check == true)
log.info ("API Response match DB results")
else{
log.info ("API response do not match DB results")
log.info(singleNode)
}

 

 

 

 

 

 

  • New2API's avatar
    New2API
    Frequent Contributor

    Hello, hyphen in a json node is tricky but you can overcome this by enclosing that node in a square brackets([])

     

    for ex: 

    I have saved your Json response in a file and I am reading it from there.

     

    import net.sf.*
    import net.sf.json.*
    import net.sf.json.groovy.*
    import groovy.json.JsonSlurper
    import groovy.io.FileType

     

    log.info "Parsing JSON payload..."

     

    //## READ canned request from a file to modify ##//
    def MyJSON = new File("C:\\TestFolder\\SampleJson.txt").text
    def JsonNodes = new JsonSlurper().parseText MyJSON

    log.info JsonNodes.data[0]["lab-term"]

     

    hope this helps!

  • nmrao's avatar
    nmrao
    Champion Level 3

    You can do something like below:

     

    def str = """{
    "data": [ {
       "rentincrease": 290,
       "effectiveprice": 1305,
       "lab-term": 1
      }
    ]
    }"""
    json = new groovy.json.JsonSlurper().parseText(str)
    //Use quotes below
    log.info json.data[0].'lab-term'