Announcements
This site is in read only until July 22 as we migrate to a new platform; refer to this community post for more details.
Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Elements in capital letter in XML to JSON Policy

I am converting XML to JSON, but my backend expects all elements in capital letters

currently:  

<x><xy>123</xy></x>
But backends expects 

<X><XY>123</XY></X>

1 1 259
1 REPLY 1

Assuming you mean your backend expects a "capitalized" JSON, you can have a JavaScript policy after converting from XML to JSON, and that JavaScript can capitalize the JSON payload for you. 

This sample assumes you have a XML to JSON policy doing the conversion, overwriting the request message object:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<XMLToJSON continueOnError="false" enabled="true" name="XML-to-JSON-1">
    <DisplayName>XML to JSON-1</DisplayName>
    <Properties/>
    <Format>yahoo</Format>
    <OutputVariable>request</OutputVariable>
    <Source>request</Source>
</XMLToJSON>

A JavaScript policy can be placed after the conversion, and the sample code below can capitalize your JSON. You might need to do some changes based on the complexity of your payload.

function capitalize(object) {
  var isArray = Array.isArray(object);
  for (var key in object) {
    var value = object[key];
    var newKey = key;
    if (!isArray) {
      delete object[key];
      newKey = key.toUpperCase();
    }
    var newValue = value;
    if (typeof value != "object") {
      if (typeof value == "string") {
        newValue = value.toUpperCase();
      }
    } else {
      newValue = capitalize(value);
    }
    object[newKey] = newValue;
  }
  return object;
}

var object = JSON.parse(context.getVariable("request.content"));
var capitalizedJson = capitalize(object);
context.setVariable("request.content", JSON.stringify(capitalizedJson));