I have a Groovy code to manipulate an Array of JSON objects.
My input is like the following (name: accounts):
[
{
"F57UI02A_AID": "00206847"
},
{
"F57UI02A_AID": "00206855"
},
{
"F57UI02A_AID": "00206852"
}
]
And I need to manipulate it to add to each internal JSON a sequence number. The expected output is:
[
{
"F57UI02A_AID ": "00206847",
"Sequence ": "1"
},
{
"F57UI02A_AID": "00206855",
"Sequence ": "2"
},
{
"F57UI02A_AID ": "00206852",
"Sequence ": "3"
}
]
In my code, I’m collecting all F57UI02A elements to get the number’s list. Then, I iterate over each JSON element, in order to create a new single one, having both F57UI02A element and the sequence number that I want to assign.
def accountList = accounts.collect{ it.get("F57UI02A_AID") };
int size = accounts.size();
def currentElement = new JsonBuilder();
String sequence = "";
def outputArray = [];
for (int i = 0; i < size; i++){
sequence = i+1;
currentElement F57UI02A_AID: accountList[i], Sequence: sequence;
outputArray[i] = currentElement;
//outputArray << currentElement;
}
returnMap.put("output", outputArray);
return returnMap;
When I run a test, I obtain the following output, instead the expected one:
[{"F57UI02A_AID":"00206852","Sequence":"3"}, {"F57UI02A_AID":"00206852","Sequence":"3"}, {"F57UI02A_AID":"00206852","Sequence":"3"}]
Do you know why I’m getting three instances of the last JSON element, instead of having the correct number/sequence in the output?
2
Answers
Sounds like you fixed your issue, but here is an idea on how to do this leveraging more features of Groovy:
Would like to add to the previous answer as there are a few more groovy things we can employ:
produces the same output as the code in the accepted answer.