user3282910
user3282910

Reputation: 1

Convert XML to json from Groovy

I want to code xml to json using groovy..i have the following code..but from the output {"note":[{"to":["Tove"]},{"from":["Jani"]},{"heading":["Reminder"]}]} i want to remove "[]" things from the output and how can i remove those things.. code as follows

def xml = '''<root>
        |    <node>Tim</node>
        |    <node>Tom</node>
        |    <node>
        |      <anotherNode>another</anotherNode>
        |    </node>
        |</root>'''.stripMargin()

// Parse it
def parsed = new XmlParser().parseText( xml )

// Deal with each node:
def handle
handle = { node ->
  if( node instanceof String ) {
      node
  }
  else {
      [ (node.name()): node.collect( handle ) ]
  }
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
   [ (node.name()): node.collect( handle ) ]
} ]

// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )

// Check it's what we expected
assert json.toString() == '{"root":[{"node":["Tim"]},{"node":["Tom"]},{"node":         [{"anotherNode":["another"]}]}]}'

Upvotes: 0

Views: 2164

Answers (1)

tim_yates
tim_yates

Reputation: 171144

You could write a function to return a single object (if the list is of length 1), or the list (if it contains more than one element):

def crush = { list ->
    list?.size() == 1 ? list[ 0 ] : list
}

Then wrap both your collect calls in a call to this method:

  [ (node.name()): crush( node.collect( handle ) ) ]

Upvotes: 1

Related Questions