Search Array and Set Environment Variables - postman

My Postman response body is this:
{
"jobs": [
{
"id": "00d21be0",
"name": "IT Department"
},
{
"id": "h27da349",
"name": "Car Sales"
},
{
"id": "5d2db4125",
"name": "Grocery Clerk"
},
{
"id": "65cd0cc1d",
"name": "Accounting Department"
},
{
"id": "8462284587",
"name": "Nurse"
},
{
"id": "9fe2ff9ee4",
"name": "Astronaut"
},
{
"id": "f40cb44799",
"name": "Phone Operator"
},
{
"id": "f4e0483257",
"name": "Project Leader"
}
]
}
What I would like to do is parse this response and set an Environmental Variable for id's associated with Nurse, Astronaut, and Grocery Clerk. The rest of the info I do not need. I cannot use the array [number] because its not a guarantee they come in the same order on other systems.
Is JSON.stringify response body the way to go? How do I pull those values?
My Postman test so far is:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentalVariable("jobs", JSON.stringify(jsonData));

What you can do is parse your json body with a loop and, when you hit the names you want, you set a global variable with the corresponding id, like :
// get the response body
var jsonData = JSON.parse(responseBody);
// init counter
var loop_count = 0
for (count = 0; count < jsonData.jobs.length; count++)
{
if (jsonData.jobs[count].name == "Nurse")
{
var job_id = jsonData.jobs[count].id;
postman.setEnvironmentalVariable("env_nurse", job_id);
}
}
This is the principle.
You can do if/else for the different names you want to catch but I don't recommend it (use an array that you can expand easily).
Same thing for the environment variable name, instead of hard coding, try to generate it with respect to your element name.

Related

Access an Array Item by index in AWS Dynamodb Query Results "Items" in Step Function

I have this dynamodb:Query in my step function:
{
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:dynamodb:query",
"Next": "If nothing returned by query Or Study not yet Zipped",
"Parameters": {
"TableName": "TEST-StudyProcessingTable",
"ScanIndexForward": false,
"Limit": 1,
"KeyConditionExpression": "OrderID = :OrderID",
"FilterExpression": "StudyID = :StudyID",
"ExpressionAttributeValues": {
":OrderID": {
"S.$": "$.body.order_id"
},
":StudyID": {
"S.$": "$.body.study_id"
}
}
},
"ResultPath": "$.processed_files"
}
The results comes in as an array called Items which is nested under my ResultPath
processed_files.Items:
{
"body": {
"order_id": "1001",
"study_id": "1"
},
"processed_files": {
"Count": 1,
"Items": [
{
"Status": {
"S": "unzipped"
},
"StudyID": {
"S": "1"
},
"ZipFileS3Key": {
"S": "path/to/the/file"
},
"UploadSet": {
"S": "4"
},
"OrderID": {
"S": "1001"
},
"UploadSet#StudyID": {
"S": "4#1"
}
}
],
"LastEvaluatedKey": {
"OrderID": {
"S": "1001"
},
"UploadSet#StudyID": {
"S": "4#1"
}
},
"ScannedCount": 1
}
}
My question is how do i access the items inside this array from a choice state in a step function?
I need to query then decide something based on the results by checking the item in a condition in a choice state.
The problem is that since this is an array I can't access it using regular JsonPath (like with Items.item), and in my next step the choice condition does NOT accept an index like processed_files.Items['0'].Status
Ok so the answer was so simple all you need to do is use a number instead of string for the array index like this.
processed_files.Items[0].Status
I was originally mislead by an error I received which said that it expected a ' or '[' after the first '['. I mistakenly thought this meant it only accepts strings.
I was wrong, it works like any other array.
I hope this helps somebody one day.

Find nested variable inside json payload

I'm using the find function in postman tests to save environment variables,
the find function works great when I'm looking for a variable, But I cannot get it to work when looking for variables inside an object
My payload looks something like this
{
"name": "product1",
"state": {
"DefinitionId": "productcard",
"Id": "32919b8c-984e-46c3-933d-51d3c621d4cf"
},
"status": "Done"
},
{
"name": "product2",
"state": {
"DefinitionId": "productaccount",
"Id": "4999b8c-984e-46c3-933d-55d3c621d4cf"
},
"status": "NotDone"
},
with the _find function I can find variables through the name variable
var steps = _.find(resBody, {
name: "product1",
})
pm.environment.set(steps.name, steps.state.Id);
But what If I want to search by DefinitionId?
I have tried stuffs like this
_.find(resBody, {
name.state: "product1",
}) <--did not work
_.find(resBody.state, {
name.state: "product1",
}) <--did not work [returns object object]
Thanks in advance.
This should return the an object by a DefinitionId search, if that's what you mean?
var result = resBody.find(x => x.state.DefinitionId === "productaccount");

How to verify array response values in postman test?

Expected Test Scenario: Need to validate the array response "Values" for the "Key: id".
I am using the test code:
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.contains(16);
});
Getting the error:
AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given.
Response Body:
[
{
"id": 2,
"Name": "Hello",
"Country": "India"
},
{
"id": 4,
"Name": "thankyou",
"Country": "UK"
},
{
"id": 16,
"Name": "how are you",
"Country": "USA"
},
{
"id": 18,
"Name": "Good morning",
"Country": "Italy"
},
{
"id": 25510,
"Name": "Bonjour",
"Country": "France"
}
]
Anyone could help me in sorting out this please.
The response is not a JSON object but JSON array.
pm.response.json() will have you full json which is in the form :
[ {}, {} ]
so the JSON object with id 16 is the 3rd element in the array so first call jsonData[3] and then get id in it.
But still you will get error because what you are getting is a "integer" so cannot use contains with it . Use equal instead
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData[2].id).to.equal(16);
});
or if you want to use contains instead , then get response as text using pm.response.text():
pm.test("Your test name", function () {
var jsonData = pm.response.text();
pm.expect(jsonData).to.contains(16);
});

Extract specific users comments from a list using Wikipedia API and Python 2.7

I am using the wikipedia API - wikitools package to extract some data from Wikipedia. I get the output of the format shown below and now I want to extract the timestamp and the comment for revisions made of specific user for several pages. Let's say I just want the comments made by TechBot, then I figured that I can do something like:
for revision in res["query"]["pages"]["7940378"]["revisions"]:
if revision["user"] = "Techbot":
do.something()
But the problem is ["7940378"] because this is a unique page id and will change for every page and I dont know how to get the pageid. Is there another way of doing this?
[{
"query": {
"pages": {
"7940378": {
"ns": 0,
"pageid": 7940378,
"revisions": [
{
"comment": "robot Modifying: [[az:T\u00fcrk Tarixi]]",
"timestamp": "2009-01-03T19:47:11Z",
"user": "TechBot"
},
{
"comment": "",
"timestamp": "2009-02-14T02:07:49Z",
"anon": "",
"user": "88.231.237.130"
},
{
"comment": "fixing recent deletion by merging it with the next paragraph",
"timestamp": "2009-04-03T14:49:27Z",
"user": "Soap"
},
{
"comment": "robot Modifying: [[az:T\u00fcrk tarixi]]",
"timestamp": "2009-04-09T14:35:19Z",
"user": "RibotBOT"
},
{
"comment": "Repairing link to disambiguation page - [[Wikipedia:Disambiguation pages with links|You can help!]]",
"timestamp": "2009-06-12T23:55:55Z",
"user": "J04n"
}
],
"title": "History of the Turkic peoples"
}
}
},
"continue": {
"rvcontinue": "20090807172715|306635892",
"continue": "||"
},
"warnings": {
"main": {
"*": "Unrecognized parameter: 'user'"
}
}
}]
Instead of using a single for loop. you can split up into two loops, where the outer loop gets the pages, and with the inner loop you can get to the revisions.
for pageid, pagedetails in res["query"]["pages"].iteritems():
for revision in pagedetails["revisions"]:
if revision["user"] == "TechBot":
do.something()

AlpacaJS: programmatically change value of TextField after selecting Select

I'm new to AlpacaJS and getting crazy trying to figure out how to do a simple stuff like changing dinamically the content of a text field with the value of a "Select".
The code looks like
$("#form1").alpaca({
"data": {
"name": "Default"
},
"schema": {
"title": "What do you think of Alpaca?",
"type": "object",
"properties": {
"name": {
"type": "string",
"title": "Name"
},
"flavour":{
"type": "select",
"title": "Flavour",
"enum": ["vanilla", "chocolate", "coffee", "strawberry", "mint"]
}
}
},
"options": {
"helper": "Tell us what you think about Alpaca!",
"flavour": {
"type": "select",
"helper": "Select your flavour.",
"optionLabels": ["Vanilla", "Chocolate", "Coffee", "Strawberry", "Mint"]
}
}
},
"postRender": function(control) {
var flavour = control.childrenByPropertyId["flavour"];
var name = control.childrenByPropertyId["name"];
name.subscribe(flavour, function(val) {
alert("Val = " + val);
this.schema.data = val;
this.refresh();
});
}
});
I can see that the function in postRenderer is called (as I can see the alert with relevant value) but (maybe I'm brain dead at this stage) I cannot refresh the text field with that value.
Cheers
I was probably looking at the wrong attribute to be set... After I changed to
this.schema.data = val;
it worked fine :)