3

I need to send a Json to an endpoint but I need to replace a key with a variable.

I've this code

 .....  

  * def idJson = response.id

  Given path <mypath>
  And headers {Authorization: '#(auth)'}
  And request read('classpath:myjson.json')
  .....

The myjson.json file is

{ "a": { ... "b":false, "c":true }, "d": { '#(idJson)': { "Key":[ ..... ] } } }

But the value is not replace in the json. When I perform the request I see that the json contains the string '#(idJson)' instead of the value of the variable. Any idea about how to solve this?

Thank you

mdotb
  • 33
  • 3

1 Answers1

1

Embedded expressions cannot be used to modify a JSON key. You have to use a JS operation like this:

* def idJson = 'foo'
* def body = {}
* body[idJson] = 'bar'
* url 'https://httpbin.org/anything'
* request body
* method post
* status 200
* match response.json == { foo: 'bar' }

Note that d could be replaced like this so you can still read the file and be dynamic:

{ "d": "#(temp)" }

And temp can be JSON that is defined in your feature before reading the file.

If this is too troublesome, please contribute code :)

Peter Thomas
  • 54,465
  • 21
  • 84
  • 248