Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON response to build additional Paw request?

Tags:

json

paw-app

https://paw.cloud/

I have the following JSON coming back from a different API end point:

[
  {
    "id": 1,
    "name": "BigCartel",
    "slug": "bigcartel",
    "logo_cdn_url": "http://placehold.it/200x200",
    "active": true,
    "authentication_type": {
      "description": "Oauth Authentication Token",
      "slug": "oauthauthenticationtoken"
    }
  },
  {
    "id": 2,
    "name": "Lightspeed Retail",
    "slug": "lightspeed_retail",
    "logo_cdn_url": "http://placehold.it/200x200",
    "active": true,
    "authentication_type": {
      "description": "Oauth Authentication Token",
      "slug": "oauthauthenticationtoken"
    }
  }
]

I would like to parse this JSON and use it in another section of the paws application. Has anyone found any examples like this? I was trying the custom JS text but that appears to be a dead end.

like image 999
Chris Hough Avatar asked Sep 07 '16 22:09

Chris Hough


1 Answers

Solution 1: jq

According to their website, "jq is a lightweight and flexible command-line JSON processor". And you can do jq queries in Paw. We will use it to automatically extract the ID of the field from your latest response.

On the URL field (where you want to have this "smart ID"), right-click and pick "jq JSON processor".

Pick jq JSON processor in Paw to extract fields from jq

In the "JQ args" field, enter the query (see jq tutorial for details on how this works):

.[] | select(.slug == "bigcartel") | .id

In the JSON input field, right-click and pick Response > Response Raw Body. A popover will open, point the "Request" field to the request from which you want to extract the response body from (your "list" request). This will automatically fetch the body of the latest response of this request.

All done! You should now have this setup:

Filter with jq the JSON body of an HTTP response in Paw

Solution 2: JavaScript Snippet

Paw exposes JavaScript bindings to write extensions (e.g. jq dynamic value used above is written as an extension). It can also be used to embed little code snippets inline a request. It's helpful to achieve more advanced setups.

Right-click on the URL field where you need to insert your ID. Pick Extensions > JS Script. In the popover, paste this code:

function evaluate(context){
    var request = context.getRequestByName("List");
    var httpExchange = request.getLastExchange();
    var body = JSON.parse(httpExchange.responseBody);
    for (var i = 0; i < body.length; i++) {
        var member = body[i];
        if (member.slug == "bigcartel") {
            return member.id;
        }
    }
    return null;
};

You can find the docs of this JavaScript API that Paw exposes in the Paw documentation under the "API Reference" section at the bottom.

like image 182
Micha Mazaheri Avatar answered Oct 31 '22 14:10

Micha Mazaheri