XML to JSON policy single array element

I am trying to convert XML to JSON using the XML to JSON policy.

When I have the following XML

<team>
    <employee>
      <name>Joe</name>
      <surname>Bloggs</surname>
  </employee>
  <employee>
    <name>Jane</name>
    <surname>Doe</surname>
  </employee>
</team>

this converts perfectly to

{
  team:{
    employee:[
      {
        name:'Joe',
        surname:'Bloggs'
      },
      {
        name:'Jane',
        surname:'Doe'
      }
    ]
  }
}

when there is only one employee this is converted to an object instead of an array:

<team>
    <employee>
      <name>Joe</name>
      <surname>Bloggs</surname>
  </employee>
</team>

converts wrongly to

{
  team:{
    employee:{
      name:'Joe',
      surname:'Bloggs'
    }
  }
}

Hov can I instead get the result

{
  team:{
    employee:[
      {
        name:'Joe',
        surname:'Bloggs'
      }
    ]
  }
}

Thank you so much for your help! :slight_smile:

3 Likes

Dear @Anders Bilfeldt ,

I believe you can able to convert response payload using javascript policy available in Apigee Platform. For more details look at @Mike Dunker Article here which explains “Converting between XML and JSON”.

Take a look at JavaScript library, called JSMapr, that allows you to specify simple transformation steps to modify a JavaScript object in place.

Cheers,

Anil Sagar

Dear @asagar

Thank you for your answer. I am wondering if it wouldn’t be easiest to use a JavaScript call that is only used if $.team.employee.name != ‘’ that could perhaps be a JSMapr JavaScrtipt.

I just can’t figure out how the Javascript should then look like.

Thanks to the person (user1591670) who posted - http://stackoverflow.com/a/23249605, this works for me.

1 Like

This is brilliant! Thank you so much :slight_smile:

this question has been answered cleanly, here:Tutorial: the TreatAsArray option in the XMLToJSON... - Google Cloud Community

1 Like

This a beautiful way of doing it. Thanks.