jsongroovyjsonbuilder

How to convert xml to json in Groovy?


In groovy I have the below xml

<data>
   <row>
      <id>USA</id>
      <value>United States of America</value>
   </row>
   <row>
      <id>CAN</id>
      <value>Canada</value>
   </row>
</data>

I need to transform the above xml in groovy to the below json format

{
   "data": [
      {
         "KEY": "USA",
         "VALUE": "United States of America"
      },
      {
         "KEY": "CAN",
         "VALUE": "Canada"
      }
   ]
}

Any help would be greatly appreciated.

Thanks

Hari


Solution

  • Here you go:

    //Pass xml as string to below parseText method
    def parsed = new XmlSlurper().parseText(xml)
    //Create the map as needed out of parsed xml
    def map = [(parsed[0].name): parsed.'**'
      .findAll{it.name() == 'row'}
      .collect{ row ->
         row.collectEntries{[KEY: row.id.text(), VALUE:row.value.text()]}
       }
    ]
    println new groovy.json.JsonBuilder(map).toPrettyString()
    

    You can quickly try it online Demo