Hello! Iāve searched for a similar post but didnāt see oneā¦sorry if I missed it.
I have a postman request that returns many JSON objects, essentially a list of reports and many details about each report. As part of my tests, I have code that randomly selects an id of one of the reports, and assigns it to a postman environment variable:
var reportJsonData = JSON.parse(responseBody);
pm.environment.set(āreportIDā, reportJsonData[Math.floor(Math.random()*reportJsonData.length)].id);
This works, but I now need to randomly select a report id from the past 60 days. Ideally, Iād like to JSON.parse only reports with a ācreatedā date > today - 60 days. Is there a way to add a condition like that to JSON.parse? Is there a better or easier way to do this? Iām still learning javascript, so any help is greatly appreciated.
Hi @ed_truqc,
You can make use of filter and MomentJS thatās included with Postman to filter your JSON array based on the created date. Assuming your created is of date type. You can use the following sample snippet to filter your array.
let moment = require('moment'),
dateToday = moment();
filteredJSONData = reportJSONData.filter((reportJSON) => {
// reportJSON.created is the created attribute that is in your array
return dateToday.diff(reportJSON.created, 'days') > 60;
});
console.log(filteredJSONData);
Your filterJSONData will have all the records with the filter (60 days here)
Thank you so much for this suggestion! It started me down the path I needed to go and I was able to figure out a way to do this. Thanks again for your time.