How do I setting a value of a key in a json body with a variable?

Viewed 24

I am trying to set the variable MY_VARIABLE in a json object.

* def MY_VARIABLE = 'USER_1'
* def loginRequestJson = { user: MY_VARIABLE , name: 'Some Name'}
* print loginRequestJson

but it outputs MY_VARIABLE as a string literal and not the the value from MY_VARIABLE as I expected.

{ "user": "MY_VARIABLE", "name": "Some Name" }

I know I can do string concatenation, but this starts looking messy with more than 5 variables.

* def loginRequestJson = "{ 'user': "+ MY_VARIABLE +" , 'name': 'Some Name'}"

Is there a more elegant way of getting my variable into the json?

PS Maybe I am thinking in a Pythonic way with dictionaries which may have not been the intention.

1 Answers

Yep, Karate is a bit different. Please take a minute to read this: https://github.com/intuit/karate#embedded-expressions

But the Pythonic or JavaScript-ish way is possible if you add round brackets:

* def MY_VARIABLE = 'USER_1'
* def loginRequestJson = ({ user: MY_VARIABLE , name: 'Some Name'})

But the preferred way in Karate is:

* def MY_VARIABLE = 'USER_1'
* def loginRequestJson = { user: '#(MY_VARIABLE)' , name: 'Some Name'}

You can choose.

Related