Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
            }
        }
    }
}

?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading