1

How do I sort and array of json that needs sorting by date using Dataweave 2

{
 "things": [
  {
    "datetime": "2020-11-07T16:11:52.866Z",
    "name": "foo"
  },
  {
    "datetime": "2020-11-07T16:11:39.971Z",
    "name": "bar"
  },
  {
    "datetime": "2020-11-07T16:11:39.978Z",
    "name": "baz"
  }
 ]
}
aled
  • 21,330
  • 3
  • 27
  • 34
blank
  • 17,852
  • 20
  • 105
  • 159
  • The input is invalid. It is missing the curly brackets around the object. I'll edit it. – aled Nov 09 '20 at 17:31

2 Answers2

2

You can use the orderBy function

%dw 2.0
output application/json
---
orderedDates: (payload.things orderBy $.datetime)

By default the output is in ascending order.

If you need descending you can do this:

%dw 2.0
output application/json
---
orderedDates: (payload.things orderBy $.datetime)[-1 to 0]

Also you can use datetime formatting if you get inputs with different timezones. With your current input values you can use LocalDateTime

%dw 2.0
output application/json
---
orderedDates: (payload.things orderBy ($.datetime as LocalDateTime {format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}))
  • THis seems to break on 2021-01-25T12:57:48.2Z - but not on 2021-01-25T12:57:48.20Z or 2021-01-25T12:57:48.200Z - and also if the breaking string is the only one in the list then that's ok – blank Jan 25 '21 at 14:44
1

Just use orderBy() and select the field with the date-time.

%dw 2.0
output application/json
---
payload.things orderBy ((item, index) -> item.datetime)
aled
  • 21,330
  • 3
  • 27
  • 34