jsongroovyjsonbuilder

groovy jsonBuilder for array of json keys


Expected json as follow

I have a list of locations and list of cubicals

{
    "Company": "my company",
    "Locations": {
        "India": {
            "cubicals": [
                "A-8954","B-3212"
            ]
        },
        "USA": {
            "cubicals": [
                "A-8954","B-3212"
            ]
        }
    }
}

Written groovy code as follow, cubicalList and nationsList is as mensioned

cubicalList=["A-8954","B-3212"]
nationsList=["India", "USA"]
def json = new groovy.json.JsonBuilder()
name="my company"
json {
    company name
    Locations {
            "${nationsList}" (
            {
                cubicals cubicalsList
            }
            )
    }
}

println json.toPrettyString()

Here India and USA coming together, any input on this will be very useful

{
    "company": "my company",
    "Locations": {
        "[India, USA]": {
            "cubicals": [
                "A-8954",
                "B-3212"
            ]
        }
    }
}

Solution

  • You mean like

    json {
        company name
        Locations {
            nationsList.each { nation ->
                "${nation}" {
                    cubicals cubicalsList
                }
            }
        }
    }
    

    ?