0

I try to include a dynamic array in a json variable and it fails.

hostsArray is dynamically built

# sample of hostsArray 
* def hostsArray = '[{"hostid": "1234"},{"hostid": "4567"}, {"hostid": "9865"}]'

* def myjson =
"""
{
  "key1": "val1",
  "params" : {
     "key2": "val2",
     "hosts" : #(hostsArray)
  }
"""

expected json:


{
  "key1": "val1",
  "params" : {
     "key2": "val2",
     "hosts" : [
          {"hostid": "1234"},
          {"hostid": "4567"}, 
          {"hostid": "9865"}
       ]
  }

I always got an error or a string, when using '#(hostsArray)' instead of the array structure

Is there a way to do that?

Thanks

2 Answers 2

1

your hostsArray is being treated as a string, not a real JSON array. When you do:

* def hostsArray = '[{"hostid": "1234"},{"hostid": "4567"}, {"hostid": "9865"}]'

that’s just a string. So when you inject it with #(hostsArray) you’ll only get a string value, not an array.
Remove the single quotes so Karate treats it as JSON:

* def hostsArray =
"""
[
  {"hostid": "1234"},
  {"hostid": "4567"},
  {"hostid": "9865"}
]
"""

Or, if you definitely want to work with strings, parse it first, then use it :

* def hostsArray = '[{"hostid":"1234"},{"hostid":"4567"},{"hostid":"9865"}]'
* def hostsArray = karate.fromJson(hostsArray)
Sign up to request clarification or add additional context in comments.

Comments

0

I finally found a way to do that. Thanks to Rajeev KR answer which drive me to the solution

The hostArray string has to be converted to JSON and it can be done using with a type conversion to json https://github.com/karatelabs/karate#type-conversion

# sample of hostsArray 
* def hostsArray = '[{"hostid": "1234"},{"hostid": "4567"}, {"hostid": "9865"}]'
* json hostArrayJson = hostsArray

* def myjson =
"""
{
  "key1": "val1",
  "params" : {
     "key2": "val2",
     "hosts" : '#(hostsArrayJson)'
  }
"""

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.