paw-app

How to traverse object with dynamic keys in Paw?


Let's say we have the following JSON response:

{
  "abcd1234": {
   "foo": "bar"
 }
}

How would "bar" be accessed in a response parsed body value? In the response, "abcd1234" could be anything. But we want the first key in the object (in JavaScript this would be Object.keys(res)[0]).


Solution

  • Paw makes it easy to parse JSON (and XML) responses and access subfields via their key-path.

    This documentation article may help: https://paw.cloud/docs/advanced/reuse-values-from-previous-responses

    Insert the Response Parsed Body dynamic value

    Insert the Response Parsed Body dynamic value

    Set the input request and extract the needed value

    Set the input request and extract the needed value

    In your example, the key path will be:

    abcd1234.foo
    

    Though, it seems like you need to access the path without knowing the key before hand. If so, one way would be to use a JavaScript snippet to be able to achieve the behavior you want.

    On any field, you may right-click and pick Extensions > JS Script.

    Here's a snippet that may fit your needs:

    function evaluate(context){
        var request = context.getCurrentRequest();
        var exchange = request.getLastExchange();
        var body = JSON.parse(exchange.responseBody);
        var key = Object.keys(body)[0];
        var value = body[key].foo;
        return value;
    };