skip to Main Content

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


  1. Sounds like you fixed your issue, but here is an idea on how to do this leveraging more features of Groovy:

    import groovy.json.*
    
    String input = """[ 
       { "F57UI02A_AID": "00206847" }, 
       { "F57UI02A_AID": "00206855" }, 
       { "F57UI02A_AID": "00206852" } ]
    """
    List<Map> json = new JsonSlurper().with { it.parseText( input ) }
    List<Map> output = json
       .findAll { it["F57UI02A_AID"] }
       .withIndex()
       .collect { 
          def (Map current, int seq) = it
          current.Sequence = seq + 1
          current
       }
    println( JsonOutput.toJson( output ) )
    
    Login or Signup to reply.
  2. Would like to add to the previous answer as there are a few more groovy things we can employ:

    import groovy.json.*
    
    String input = '''[ { "F57UI02A_AID": "00206847" }, 
                        { "F57UI02A_AID": "00206855" }, 
                        { "F57UI02A_AID": "00206852" } ]'''
    
    def json = new JsonSlurper().parseText( input ) 
    def output = json.findAll { it["F57UI02A_AID"] }
                     .indexed(1)
                     .collect { i, m -> m + [Sequence: i] }
    println( JsonOutput.toJson( output ) )
    

    produces the same output as the code in the accepted answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search