karate

Transforming API Payload into Nested JSON Structure


I received the following response from an API:

{
  "id": 306,
  "FieldName": "customer.info.User",
}

Based on the FieldName attribute from this response, I need to construct a payload for another API with the expected output as follows:

Below is the expected output I need.

{
  "customerList": [
    {
      "customerConditionHeader": {
        "entityType": "CORPORATIONS",
        "country": "FOR_ALL",
        "entityRole": "CUSTOMER"
      },
      "customer": {
        "info": {
          "user": "some_value"
        }
      }
    }
  ]
}

Solution

  • I'm going to focus on only part of your JSON and leave a hint.

    The karate.set(variableName, path, value) API can do some very special things. For example:

    * def response = { id: 306, FieldName: 'customer.info.user' }
    * def payload = {}
    * karate.set('payload', response.FieldName, 'some_value')
    * match payload == { customer: { info: { user: 'some_value' } } }
    

    Note how customer.info.user got blown up into JSON. I leave the rest to you to figure out and you can use JS for more weird transformations. Refer other answers for more tips, for e.g: https://stackoverflow.com/a/76091034/143475 and https://stackoverflow.com/a/53120851/143475