'Azure Logic App - order CSV by specified column

I have a Logic App in Azure, which has a 'Create CSV table' step. The input to the 'Create CSV table' step comes from a preceding 'Liquid Transform JSON' step. I want to order the CSV file by a particular column. Is there a way I can do this easily in the 'Create CSV table' step? Or, do I need to transform the JSON first somehow, in a step between the 'Liquid Transform JSON' and the 'Create CSV table' step?

The JSON that is output from the 'Liquid Transform JSON' step is in this format, and I want to sort by UTCTimeStamp ascending:

[
  {
    "TransactionType": "Alert",
    "UTCTimeStamp": "2022-05-16T03:29:23.704735Z"
  },
  {
    "TransactionType": "Alert",
    "UTCTimeStamp": "2022-05-15T23:58:14.867664Z"
  }
]

I tried sorting in the Liquid template, but as described here the sort works for basic data, but there doesn't seem to be a way to sort by a specific JSON property in a Liquid template, when the JSON is an array of more complex objects.



Solution 1:[1]

You can sort your JSON using 'Execute JavaScript Code' action between your 'Liquid Transform JSON' and 'Create CSV table' actions.

E.g. if you wanted to sort the "content" array from the following JSON array by Name -

{
  "content": [
    {
      "Identifier": "1",
      "Name": "B"
    },
    {
      "Identifier": "2",
      "Name": "A"
    }
  ]
}

Compose

you could use the following JavaScript code:

var arr = workflowContext.actions.Compose.outputs.content;
return arr.sort(GetSortOrder());

function GetSortOrder() {    
    return function(item1, item2) {
        return (item2.Name < item1.Name) ? 1 : (item1.Name < item2.Name) ? -1 : 0;    
    }    
}

Execute JavaScript Code

Result:

[
  {
    "Identifier": "2",
    "Name": "A"
  },
  {
    "Identifier": "1",
    "Name": "B"
  }
]

Solution 2:[2]

See the answer from @10p, which shows how to access and sort the JSON output of a previous step using an 'Execute JavaScript Code' action.

To order by UTCTimeStamp value ascending in the sample data structure I provided in the question, I used the following in an 'Execute JavaScript Code' action following the Liquid_Transform_JSON step:

var arr = workflowContext.actions.Liquid_Transform_JSON.outputs.body;
return arr.sort(GetSortOrder());

function GetSortOrder() {    
    return function(item1, item2) {
        return Date.parse(item1.UTCTimeStamp) - Date.parse(item2.UTCTimeStamp) 
    }    
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 10p
Solution 2 Chris Halcrow