Monthly Archives: May 2023

Postman Variables and Scripts

Tired of updating your json payload (attribute) let Postman do it for you with a script and variable

Sometimes you need to generate new timestamps or id’s or … for every new request you send with POSTMAN. The solution is to use pre-request scripts. These scripts are Javascripts that will use macros to populate values in your body content (json in my case).

With the following JSON

And the following pre-request script

then you can get the following result

Inserting a json attribute from one query into another using a script and variable

In my case I was first querying to get a authentication token CSRF_NONCE that I should use in the forthcoming queries as a header.

Step 1) Query for a token

GET https://my.super-secret.server.com/api/security/csrf

Using Basic Authentication (Username/Password)

I would get back a json payload like this

Now let’s create a script that extracts that nonce token

NOTE ! You use “Post-response” script to the left

The script could be something like this

Step 2) Query for the data

Add the header attribute CSRF_NONCE in my case, and set the value to {{NONCE}} which was the variable you set above in the script.

After the query in Step 1) has been executed you can verify that the global variable has received the right value by going to the following view

You can also see the value in the POSTMAN Console

jq to the rescue

JQ is a really good tool when you have lot of JSON and you just interested in some of that data.

What if I just want to count number of entries in a list

Imagine I have this

And now you want to know how many entries there are in that array/list

jq query is so simple

. | length

(dot pipe length)

and the result is simply the number of elements e.g. 5

Only see the first N entries in an array (list)

.[:3]

The above would result in returning the first 3 entries in the array (list)

Only see some attributes

Imagine you have a JSON like this, and you only want to see the “name” attribute

(extract specific attributes from a json array with objects, from array to array)

the JQ query would then be something like this

[.[] | { “email” : .email } ]

and that would give you the following output

You can use jqpplay, JQ Kung Fu and other online alternatives to try it out, and ofcourse the command line ‘jq’ command.

Just a list of strings for one “column” / attribute

If you want to just create an array of strings, then you try this jq query

[.[] | .email ]

Which would give you the following

JSON to CSV

You will the following output with lots of quotes

That is not so nice, so to avoid the quotes then use the “Raw Output” function
then the output will look like this

Much better 🙂