简体   繁体   中英

Replace a variable in a String with actual value - Groovy

In Groovy,

Consider a variable "ssn" whose value is entered by the user.

def ssn = <SSN captured via user input>

I am creating a query in form of a String "payload" where ssn entered by user should replace ssn in the string.

String payload='{"<Some Database Query>","Variables"{"Id":"${ssn}"}}';

What is wrong with the above String? ssn in the string is not replaced by ssn captured via user input. Is "${ssn}" not the right syntax to capture the variable value in a string?

Inside of a single quoted string you can't do string interpolation. You need the outer string to be double quoted. Since you want to embed double quotes in the value, the simplest way to do that is with triple double quotes ( """...""" ).

See the following:

groovy:000> ssn = 'some captured input'
===> some captured input
groovy:000> payload = '{"<Some Database Query>","Variables"{"Id":"${ssn}"}}'
===> {"<Some Database Query>","Variables"{"Id":"${ssn}"}}
groovy:000> 
groovy:000> payload = """{"<Some Database Query>","Variables"{"Id":"${ssn}"}}""" 
===> {"<Some Database Query>","Variables"{"Id":"some captured input"}}

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