简体   繁体   中英

How to escape json slurper processing the variable type values in response

I have a json response like below

{ events": [
      {
      "documentService":       {
          "key": null,
         "wsdlLocation": "${ATOKEN}://${BTOKEN}:${CTOKEN}/somesrc/ItemServiceV2?WSDL",
         
      },
      "documentTransform": null
     
   }
] 
}

and I have the below groovy script

parseText( response ) here response is above json The main aim of the script is just to list the wsdlLocation in the response

def jsonSlurper = new JsonSlurper()
Map parsedJson = jsonSlurper.parseText( response ) 

def eventsList= parsedJson.get("events")

def noOfeventnoWsdl =0;
def noOfeventyesWsdl =0;
for( def ievent: eventsList){
    if(ievent.documentService != null){
        noOfeventyesWsdl++
        log.info ievent.documentService.wsdlLocation.toString()
    }else{
        noOfeventnoWsdl++
    }
}

and execution of the result is

==> INFO:://:/somesrc/ItemServiceV2?WSDL

instead

==> INFO:: ${ATOKEN}://${BTOKEN}:${CTOKEN}/somesrc/ItemServiceV2?WSDL or whereas

ATOKEN is https

BTOKEN is hostname

CTOKEN is port

I am also ok with the below out put

==> INFO:: https://somehost:1234/somesrc/ItemServiceV2?WSDL

I just want the output either without expanding the parameter or if there is a way to inject the ATOKEN, BTOKEN,CTOCKEN in jsonSlurper context that is also fine.

Please help me.

JsonSlurper doesn't substitute or evaluate the dollar sign expressions. So I'm left to assume that the JSON string you have is defined in the source file, and what you're experiencing is GString substitution expressions. If you wish to leave the ${expression} within the Json text you'll want to escape the dollar sign like so:

"wsdlLocation": "\${ATOKEN}://\${BTOKEN}:\${CTOKEN}/somesrc/ItemServiceV2?WSDL",

The other option is to extract that out of the source files so it won't be evaluated as a GString , and move it to a proper file:

File file = new File("/path/to/file/example.json")
def json = new JsonSlurper().parse( file )

If you do the above you don't need to escape the ${} expressions in your json.

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