liquidazure-logic-appsdotliquid

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

  • 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"
      }
    ]