I was unable to find correct answer and therefore posting a question.
Return response on Postman is as below:
[
{
"AttemptNumber":1,
"LoginID":test123,
"CurrentStatus":2
}
]
I'm trying to count elements in this array object.
this is what I was doing:
countItems = JSON.pase(responseBody)
for (var i = 1, l = Object.keys(countItems).length; i <=3){
}
but I keep getting 1. 1 is array but I'm looking for count to be 3.
I'll appreciate your expertise.
Thanks.
This should log the number of items from each object in the response array:
let res = pm.response.json()
_.each(res, (obj) => {
console.log(_.keys(obj).length)
})
It's using some methods from Lodash, which is one of the built-in libraries.
https://lodash.com/docs/4.17.15
Related
I'm not sure why I'm having such a hard time finding an answer for this, but I have a list that I need to get the value from where the key matches certain criteria. The keys are all unique. In the example below, I want to get the color where the name equals "headache". Result should be "4294930176".
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
Error I get: Class '_InternalLinkedHashMap' has no instance getter 'name'. Any suggestions?
EDIT:
Here's how I'm adding the data to the list, where userDocuments is taken from a Firestore collection:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}
I guess, I got what the problem was. You were making a little mistake, and that was, you're trying to call the Map element as an object value.
A HashMap element cannot be called as f.name, it has to be called f['name']. So taking your code as a reference, do this, and you are good to go.
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
Check that out, and let me know if that helps you, I am sure it will :)
I am trying to set an array as an environmental variable in postman.
But it stores the first value of the array rather than the array.
var aDataEntry = postman.pm.environment.get('data_set_entries');
if(aDataEntry == null) {
aDataEntry = [];
}
var jsonData = pm.response.json();
aDataEntry.push(jsonData.dataEntry.id);
// a console.log here confirms that aDataEntry is an array
postman.pm.environment.set('data_entry',aDataEntry);
As mentioned in the comment of the code, the variable is coming as an array,
but when I again get the environment variable in the second run, it is not
of type array. But just contains the first element in the array.
What's wrong here?
How can set the array and use it from the postman environment variable.
It seems like pm.environment.set calls toString to set an environment value. You can use the below code to work-around that:
var aDataEntry = pm.environment.get('data_set_entries');
if(aDataEntry == null) {
aDataEntry = [];
} else {
aDataEntry = JSON.parse(aDataEntry);
}
var jsonData = pm.response.json();
aDataEntry.push(jsonData.dataEntry.id);
// a console.log here confirms that aDataEntry is an array
pm.environment.set('data_entry',JSON.stringify(aDataEntry));
Edit 1:
As mentioned in the Postman reference docs, it is suggested that one use JSON.stringify() and JSON.parse() for storing complex objects. I have updated the code accordingly.
I'm not sure of how you intend to use the array, but to dynamically generate an array for use in a Body > raw > JSON POST, as in the answer above you do need to actually store the var as a string.
Here's an example of that and it's use in the POST Body. I had a long list of IDs, and I'm using Postman to do some bulk user profile updates.
In the Pre-request Script, generate the string to be POSTed as an array.
var externalIds = [111,222,333,444];
var attrString = "";
externalIds.forEach(userId => {
attrString += `,{"external_id": ${userId},"my_first_attribute": false,"my_next_attribute": true}`;
});
attrString = attrString.replace(',',''); // strip out that 1st unwanted comma
pm.environment.set("attributeArray",attrString);
The saved "array", Postman console logged:
"{"external_id": 111,"my_first_attribute": false,"my_next_attribute": true},
{"external_id": 222,"my_first_attribute": false,"my_next_attribute": true},
{"external_id": 333,"my_first_attribute": false,"my_next_attribute": true},
{"external_id": 444,"my_first_attribute": false,"my_next_attribute": true}"
Looks like bad, nested double quotes, but the format is actually valid.
My Body > raw looks like:
{
"api_key": "{{api_key}}",
"attributes": [{{attributeArray}}]
}
Note the Postman variable is wrapped in "[" and "]".
If my externalIds array needed to be a pm variable, I'd store that as a string, and .split() it when using it in the Script tab.
The Postman console really helps get past the syntax mistakes.
I am facing a problem with Facebook meseger chat- bot ,problem is with Context variable storing and update .
My code is divided in two parts
_________**********_________
part 1:
var index = 0;
Facebookcontexts.forEach(function(value) {
console.log(value.From);
if (value.From == sender_psid) {
FacebookContext.context = value.FacebookContext;
console.log("Inside foreach "+JSON.stringify(FacebookContext.context));
contextIndex = index;
}
index = index + 1;
});
Here I have created an array named Facebookcontexts to store contexts for different users.This is where I am getting position of the user in a Facebookcontexts array which is used for later .
_________**************_____________
part 2:
if((FacebookContext.context==null)||(Facebookcontexts.find(v=>v.From==sender_psid)==undefined)){
Facebookcontexts.push({"From":sender_psid,"FacebookContext":response.context})
console.log("I am where sender is unknmown"+JSON.stringify(Facebookcontexts)+"\n"+Facebookcontexts.length);
}
else if(Facebookcontexts.find(v=>v.From==sender_psid)!=undefined){
Facebookcontexts[contextIndex].FacebookContext=response.context;
console.log("I am at where I know the sender"+JSON.stringify(Facebookcontexts)+"\n"+Facebookcontexts.length);
}
I am deciding to create a new record or update old one in if and else
Issue:
My Issue is every time if((FacebookContext.context==null)||(Facebookcontexts.find(v=>v.From==sender_psid)==undefined)) is getting checked and for that array length is 1 all the time
I will look for some help from you guys.
Thanks ins advance
I am trying to get first or last x items from firebase list using AngularFire2,
return this.af.database.list('classes/class-001').takeLast(3);
but I get nothing even with subscribe on the above.
Any idea?
return = af.database.list('classes/class-001', {
query: {
limitToLast: 3,
}
});
I need your help about CouchDB reduce function.
I have some docs like:
{'about':'1', 'foo':'a1','bar':'qwe'}
{'about':'1', 'foo':'a1','bar':'rty'}
{'about':'1', 'foo':'a2','bar':'uio'}
{'about':'1', 'foo':'a1','bar':'iop'}
{'about':'2', 'foo':'b1','bar':'qsd'}
{'about':'2', 'foo':'b1','bar':'fgh'}
{'about':'3', 'foo':'c1','bar':'wxc'}
{'about':'3', 'foo':'c2','bar':'vbn'}
As you can seen they all have the same key, just the values are differents.
My purpse is to use a Map/Reduce and my return expectation would be:
'rows':[ 'keys':'1','value':{'1':{'foo':'a1', 'at':'rty'},
'2':{'foo':'a2', 'at':'uio'},
'3':{'foo':'a1', 'at':'iop'}}
'keys':'1','value':{'foo':'a1', 'bar','rty'}
...
'keys':'3','value':{'foo':'c2', 'bar',vbn'}
]
Here is the result of my Map function:
'rows':[ 'keys':'1','value':{'foo':'a1', 'bar','qwe'}
'keys':'1','value':{'foo':'a1', 'bar','rty'}
...
'keys':'3','value':{'foo':'c2', 'bar',vbn'}
]
But my Reduce function isn't working:
function(keys,values,rereduce){
var res= {};
var lastCheck = values[0];
for(i=0; i<values.length;++i)
{
value = values[i];
if (lastCheck.foo != value.foo)
{
res.append({'change':[i:lastCheck]});
}
lastCheck = value;
}
return res;
}
Is it possible to have what I expect or I need to use an other way ?
You should not do this in the reduce function. As the couchdb wiki explains:-
If you are building a composite return structure in your reduce, or only transforming the values field, rather than summarizing it, you might be misusing this feature.
There are two approaches that you can take instead
Transform the results at your application layer.
Use the list function.
Lists functions are simple. I will try to explain them here:
Lists like views are saved in design documents under the key lists. Like so:
"lists":{
"formatResults" : "function(head,req) {....}"
}
To call the list function you use a url like this
http://localhost:5984/your-database/_design/your-designdoc/_list/your-list-function/your-view-name
Here is an example of list function
function(head, req) {
var row = getRow();
if (!row){
return 'no ingredients'
}
var jsonOb = {};
while(row=getRow()){
//construct the json object here
}
return {"body":jsonOb,"headers":{"Content-Type" : "application/json"}};
}
The getRow function is of interest to us. It contains the result of the view. So we can query it like
row.key for key
row.value for value
All you have to do now is construct the json like you want and then send it.
By the way you can use log
to debug your functions.
I hope this helps a little.
Apparently now you need to use
provides('json', function() { ... });
As in:
Simplify Couchdb JSON response