Dhamo
Dhamo

Reputation: 1251

Karate - Convert a Json array into another form

I have the following data and I need to modify some of the values in it for further processing in Karate.

Input Json: (ReqCalculationInput.json)

 {
  "route_parameters": {
    "route_type": "Distance",
      "enc_hazards": [
        {
          "id": 0,
          "severity": 4
        },
        {
          "id": 1,
          "severity": 4
        },
        {
          "id": 2,
          "severity": 4
        }
      ]
    }
  }
}

Output data:

{
  "route_parameters": {
    "route_type": "Distance",
      "enc_hazards": [
        {
            "id": 0,
            "severity": "Danger"
          },
          {
            "id": 1,
            "severity": "Danger"
          },
          {
            "id": 2,
            "severity": "Danger"
          }
      ]
    }
  }
}

As you can see, I need to replace all the severity values with 'Danger' from '4'.

My code so far:

        * def requestBodyJson = read('classpath:data/routing/ReqCalculationInput.json')
        * def fun = function(x){ return {if (x.severity === 4) {x.severity: "Danger"}}}
        * def formattedInput = karate.map(requestBodyJson.route_parameters.enc_hazards, fun)
        * print formattedInput

Any hints to achieve the same?

Upvotes: 1

Views: 510

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

Just for fun, I'll give you a one-liner that will work in Karate 1.X

* data.route_parameters.enc_hazards = data.route_parameters.enc_hazards.map(x => x.severity == 4 ? {id: x.id, severity: 'Danger' } : x)

Here's a more easier to understand version:

* def fun = function(x){ return x.severity == 4 ? {id: x.id, severity: 'Danger' } : x }
* data.route_parameters.enc_hazards = karate.map(data.route_parameters.enc_hazards, fun)

Upvotes: 1

Related Questions