Big Hendo Big Hendo - 3 years ago 155
Groovy Question

Try to perform a sort but the output does not appear to sort the output

I have a little issue with some sorting in my Groovy scrip and I am not sure why it is not working as expected.

Below is the JSON I am trying to sort:

I am trying to sort this JSON by 'policyid' but it doesn't seem to sort it and I have no idea why it isn't as to me the code seems correct:

def testsort = json.groups.options.flatten() testsort.sort{a,b -> a.policyid <=> b.policyid}

Below is what it is outputting:

[{passengerSeqIds=[1], policyId=34, cost=40.0000, optionalPassengerSeqIds=[]},
{passengerSeqIds=[2], policyId=31, cost=25.0000, optionalPassengerSeqIds=[]},
{passengerSeqIds=[1, 2], policyId=35, cost=72.0000, optionalPassengerSeqIds=[]}]

Below is what I want it to output:

[{passengerSeqIds=[2], policyId=31, cost=25.0000, optionalPassengerSeqIds=[]},
{passengerSeqIds=[1], policyId=34, cost=40.0000, optionalPassengerSeqIds=[]},
{passengerSeqIds=[1, 2], policyId=35, cost=72.0000, optionalPassengerSeqIds=[]}]

Answer Source

There is a typo in your code: testsort.sort{a,b -> a.policyid <=> b.policyid} 

You access policyid field while it should be policyId. Change mentioned line to: testsort.sort{a,b -> a.policyId <=> b.policyId} 

and you will get the output:

[policyId:31, passengerSeqIds:[2], optionalPassengerSeqIds:[], cost:25]
[policyId:34, passengerSeqIds:[1], optionalPassengerSeqIds:[], cost:40]
[policyId:35, passengerSeqIds:[1, 2], optionalPassengerSeqIds:[], cost:72]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download