0

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 ?

2
  • Do you have heterogeneous arrays (array with elements of different datatype) as well? Commented Nov 12, 2024 at 9:13
  • no this is pretty much the way data will be present Commented Nov 12, 2024 at 10:05

1 Answer 1

3

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 $)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.