groovyjsonbuilder

Groovy Transform json nested Structure to jsonobject from array


the input is

{
  "Id": ["A1", "A2", "A3"],
  "isAvailable": true,
  "isActive": true
}

the output should be like

{
  "Id": "A1",
  "isAvailable": true,
  "isActive": true
},

{
  "Id": "A2",
  "isAvailable": true,
  "isActive": true
},

{
  "Id": "A3",
  "isAvailable": true,
  "isActive": true
}

i tried following code but struck please help i tried json builder but not working

    def input = new JsonSlurper().parseText(inputfile);
    for (int i = 0; i < id.size(); i++){
     def output = {
                    id: id[i]
                    isAvailable:  input.isAvailable
                    isActive: input.isActive      
     }
}

Solution

  • Simple collect would do:

    import groovy.json.*
    
    def input = new JsonSlurper().parseText '{"Id": ["A1", "A2", "A3"],"isAvailable": true,"isActive": true }'
    
    def result = input.Id.collect{ input + [ Id:it ] }
    
    assert JsonOutput.prettyPrint( JsonOutput.toJson( result ) ) == '''\
    [
        {
            "Id": "A1",
            "isAvailable": true,
            "isActive": true
        },
        {
            "Id": "A2",
            "isAvailable": true,
            "isActive": true
        },
        {
            "Id": "A3",
            "isAvailable": true,
            "isActive": true
        }
    ]'''