I need to sort JSON data which can contain array as well as objects sample data :
{
"results": [
{
"empCode": "abcd",
"age": 33,
"awards": [
{
"year": 2024,
"status": [
"X1",
"FA",
"VE"
]
}
]
},
{
"empCode": "abcd",
"age": 33,
"awards": [
{
"year": 2024,
"status": [
"X1",
"FA",
"VE"
]
}
]
}
]
}
Using this script I am able to sort :
%dw 2.0
output application/json
fun sortObjects(x)=
x match {
case o is Object -> o
orderBy ((value, key) -> key)
mapObject (($$): sortObjects($))
case a is Array -> a map ((item, index) -> item match {
case abc1 is Object -> abc1
orderBy ((value, key) -> key)
mapObject (($$): sortObjects($))
else -> $
}
)
else -> $
}
---
sortObjects(payload)
So this is sorting fine based on the keys
which is fine
However I also want to sort the string array status
in ascending order as well .
Presently it appears as :
"status": [
"X1",
"FA",
"VE"
],
I would want it to appear as:
"status": [
"FA",
"VE",
"X1"
],
How do I achieve this ?
You only need to make a small correction in your script. Basically, you are not sorting array at all in case the array is not an array of Object. Also, when the array is array of objects, you can recursively call the same function since you already have the logic to sort objects written in the same function.
case a is Array -> if(a[0] is Object) a map sortObjects($)
else (a orderBy $)