Search code examples
paw-app

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.


Solution

  • 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
    }