Is there a way to add a condition to JSON.parse()?

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.

Thanks!
Ed

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)

1 Like

Hi @bhargav.karanam,

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.

Ed