Search code examples
jsondictionaryrequestkaratejsonpath

How To set a Value in an array in a map Request in Karate


thanks for reading. I am using karate for backend testing and I need to update de value of an array inside a map in my request. BUT I CANT DO IT

I am using this request;

{
  "data": [
    {
      "startDate": "date",
      "endDate": "date",
      "displayDate": "date",
      "partnerId": "partner",
      "type": "type",
      "regions": ["QQ"
      ],
      "promotionId": "promotion",
    }
  ]
}

I want to update/overwrite the "regions" value. but I cant make Karate access to it, it never finds it. I have tried:

* set request.data.regions = newValue   
* set request.data[*].regions = newValue
* set request[*].regions = newValue
* def updateRegion =
      """
      function(){karate.appendTo(request.data[*].regions, newValue) }
      """
* karate.foreach(request, updateRegion)

and nothing works. Worth saying that I am able to get the data of regions using :

* def value = get request.data[*].regions

The problem is that either Karate does not recognize jsonpath to get to the key, and throws an error:

    org.graalvm.polyglot.PolyglotException: SyntaxError: Unnamed:1:32 Expected an operand but found *
karate.appendTo(blankOffer.data[*].regions, 'table.region')

or it just does not find said key and returns null:

Cannot invoke "com.intuit.karate.core.Variable.isList()" because "var" is null

what am I doing wrong?? HELP PLEASE!


Solution

  • You need to pay attention to the structure. Try this, it is simple JS:

    * def body = 
    """
    {
      "data": [
        {
          "startDate": "date",
          "endDate": "date",
          "displayDate": "date",
          "partnerId": "partner",
          "type": "type",
          "regions": [
            "QQ"
          ],
          "promotionId": "promotion"
        }
      ]
    }
    """
    * body.data[0].regions = ['foo', 'bar']
    * print body