HI,
I have a requirement where i need to convert XML 2 JSON which has numbers and i require some of them as number and some as string, currently all are converted as numbers or as string using .
please find example below
XML input:
<a:ItemResponse>
<a:Amount>1500.0400</a:Amount>
<a:xxxxxxx>3200027662909</a:xxxxxxx>
<a:RuleBreak>1</a:RuleBreak>
<a:RuleBreakData>
<a:StatusCode>
<a:Code>4</a:Code>
<a:Message>Item Decline.</a:Message>
</a:StatusCode>
</a:RuleBreakData>
<a:kkkkkkkk>685346587648678947698</a:kkkkkkkk>
</a:ItemResponse>
Expected outPut:
{
āItemResponseā: {
āAmountā: 1500.04,
āxxxxxxxā: ā3200027662909ā,
āRuleBreakā: 1,
āRuleBreakDataā: {
āStatusCodeā: {
āCodeā: ā4ā,
āMessageā: āItem Decline.ā
}
},
ākkkkkkkkā: ā685346587648679000000ā
}
}
Here Amount should be number and remaining shiuld be String, please let me know if there is a way to do this.
1 Like
I cannot think of a way to do that with JUST the XMLToJSON policy. But you can accomplish it with two steps. First, configure the XMLToJSON policy to NOT recognize numbers. Then each numeric text value will be treated as a String. Then, add a JS policy directly after the XMLToJSON policy, which performs a manual conversion of data types. Basically it does this:
var c = JSON.parse(context.getVariable('response.content'));
c.ItemResponse.Amount = Number(c.ItemResponse.Amount);
context.setVariable('response.content', JSON.stringify(c));
1 Like
This works but, The challenge is sometimes āitem responseā is an array ,tried below code but failed,
var c = JSON.parse(context.getVariable(āresponse.contentā));
var i;
var value = c.ItemResponse.length
if (c.hasOwnProperty(āAmountā))
{
for ( i = 0; i < value; i++) {
c.ItemResponse[i].Amount = Number(c.ItemResponse[i].Amount);
context.setVariable(āresponse.contentā, JSON.stringify(c));
}
}
else
{
context.setVariable(āresponse.contentā, JSON.stringify(c));
}
Here in above code i also want to check , existence of Amount key, Number conversion should happen only if Amount is present in payload , else nothing should happen.
I am guessing that youād prefer to have the āitem responseā ALWAYS be an array. To do that, check out the TreatAsArray option in the XMLToJSON policy. It is designed for that purpose.
<XMLToJSON name=X2J-1'>
<Source>response</Source>
<OutputVariable>response.content</OutputVariable>
<Options>
<TreatAsArray>
<Path unwrap='false'>itemResponse</Path>
</TreatAsArray>
</Options>
</XMLToJSON>
And then your JS code will always work.
I already did that, and i tried above code , its not working. because āc.itemResponse.Amountā only works for object
Right. You wouldnāt be able to use my code, the example code I showed, if you are always dealing with an array. My code works with the original JSON you showed me. You would have to adjust that code to use a loop - along the lines of what you showed - to handle the case in which itemResponse is an array. Itās a small adjustment.