Search code examples
jsonpostmanpostman-testcase

How do I sort a json using a time stamp field within the json file in Postman?


I am new to Postman, I have a API call which gives me the output as a json. In the "Test", I get the JSON by "bodyData = JSON.parse(responseBody);"

The JSON file has got timestamp fields example "executedDate": "2020-11-26T09:45:27.000Z". I would need help in sorting the JSON file in descending order based on the executedDate field.

 {
   "dataflowJobs": [
    {
        "createdDate": "2020-11-26T09:45:03.000Z",
        "duration": 48,
        "executedDate": "2020-11-26T09:45:27.000Z",
        "id": "03C2w000002Urb1EAC",
        "jobType": "user",
        "label": "Dataflow_2",
        "progress": 1.0,
        "startDate": "2020-11-26T09:45:03.000Z",
        "status": "Success",
        "type": "dataflowjob",
        "url": "/services/data/v47.0/wave/dataflowjobs/03C2w000002Urb1EAC"
    },
    {
        "createdDate": "2020-11-26T09:45:01.000Z",
        "duration": 34,
        "executedDate": "2020-11-26T09:45:02.000Z",
        "id": "03C2w000002UracEAC",
        "jobType": "user",
        "label": "Adv_Dataflow_Exercises",
        "progress": 1.0,
        "startDate": "2020-11-26T09:45:01.000Z",
        "status": "Success",
        "type": "dataflowjob",
        "url": "/services/data/v47.0/wave/dataflowjobs/03C2w000002UracEAC"
    },        {
        "createdDate": "2020-11-20T09:45:01.000Z",
        "duration": 58,
        "id": "0eP2w000000MhszEAC",
        "jobType": "recipe",
        "label": "Feb_and_Jan_S2_Modified_Recipe2_recipe",
        "progress": 1.0,
        "startDate": "2020-11-20T09:45:01.000Z",
        "status": "Success",
        "type": "dataflowjob",
        "url": "/services/data/v47.0/wave/dataflowjobs/0eP2w000000MhszEAC"
    }
],
"url": "/services/data/v47.0/wave/dataflowjobs"
}

Solution

  • let moment = require('moment')
    
    
    let jsonData = pm.response.json()
    
    console.log(jsonData.dataflowJobs.sort(function (a, b) { return moment(b.executedDate).diff(moment(a.executedDate), "seconds") }))
    

    This will sort according to executed time , if there is no executed time it will be at the top