Joshua Jabbour
Joshua Jabbour

Reputation: 592

Pick random array item from response in Paw

Given the following API response, I'd like to use the "Response Parsed Body" dynamic variable and select a random id from the array:

[
  {
    "id": 1
  },
  {
    "id": "2"
  }
]

Using [0].id gives me 1, but there's no way to select a random item. This is likely a problem with JSONPath, but it would be nice to have Paw implement a way to do this.

Upvotes: 2

Views: 2523

Answers (2)

Saidamir Botirov
Saidamir Botirov

Reputation: 53

let list = JSON.parse(responseBody);
let random_num = _.random(list.length);
let randomId= list[random_num].id;
postman.setEnvironmentVariable("randomId", randomId);

Upvotes: 0

Matthaus Woolard
Matthaus Woolard

Reputation: 2408

The best way to do this is to create a custom dynamic value.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}


function evaluate(context) {
  var request = context.getRequestByName('OtherRequestName')
  var lastExchange = request.getLastExchange()
  var body = JSON.parse(lastExchange.responseBody)
  var list = body // path to list within body
  var i = getRandomInt(0, list.length)
  return list[i].id
}

Upvotes: 4

Related Questions