-1

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

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
hpandalai
  • 438
  • 2
  • 13
  • 31

1 Answers1

1

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

Rao
  • 20,781
  • 11
  • 57
  • 77
  • Just nitpicking: you don't need the `row.collectEntries{ ... }` there - the `...` is enough – cfrick Jul 06 '17 at 06:22