cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Sort field names alphabetically in JSON source data

darshthakkar
Valued Contributor

Hi Team,

I have my source data coming in JSON format. I want to sort the fields inside the JSON format alphabetically. One way is to use a mapper and arrange them one-one alphabetically but it is a tedious task if the fields are more. Can we use an expression in mapper or any other snap that does this for us?

Thank you.

Best Regards,
Darsh

1 ACCEPTED SOLUTION

AleksandarAngel
Contributor III

Hi @darshthakkar,

One approach will be to Map the input document with the following expression:

$.entries().sort((a,b) => a[0].localeCompare(b[0])).reduce((acc,curr) => acc.extend({[curr[0]]:curr[1]}),{})

Note: This will only sort properties on first level.

Let me know if this helps.

BR,
Aleksandar.

View solution in original post

12 REPLIES 12

AleksandarAngel
Contributor III

Hi @darshthakkar,

One approach will be to Map the input document with the following expression:

$.entries().sort((a,b) => a[0].localeCompare(b[0])).reduce((acc,curr) => acc.extend({[curr[0]]:curr[1]}),{})

Note: This will only sort properties on first level.

Let me know if this helps.

BR,
Aleksandar.

darshthakkar
Valued Contributor

Thank you @AleksandarAngelevski for your suggestion.
I will try it out and keep you posted with my findingsโ€ฆ

@AleksandarAngelevski - Youโ€™re right, Alphabetical sorting doesnโ€™t work on the first level so youโ€™ll have to break that hierarchy and once youโ€™re at the final stage, your expression will definitely work, Iโ€™ve tested it and can confirm that it works.

How I broke the hierarchy: Using JSON Splitter to reorganise JSON - #3 by Supratim (thank you @Supratim for your comments on a different thread)

darshthakkar
Valued Contributor

@AleksandarAngelevski - Is it a safe assumption that we can use the same expression with a minor tweak to organize data alphabetically even if itโ€™s not the JSON format?