Hello,
I'm trying to serialize JSON object into a string representation by recursively iterating and appending the key-value pairs in a specific format, where keys and values are concatenated without any separator.
Below are the expected input and output. Any suggestions on how we can achieve this in Apigee?
Input- {"Username":"merchant_username","Password":"merchant_password","NotificationURL":"URL_to_your_notification_service","EndUserID":"12345","MessageID":"your_unique_deposit_id","Attributes":{"Locale":"sv_SE","Currency":"SEK","IP":"123.123.123.123","MobilePhone":"+46709876543","Firstname":"John","Lastname":"Doe","NationalIdentificationNumber":"790131-1234"}}
Output- AttributesCurrencySEKFirstnameJohnIP123.123.123.123LastnameDoeLocalesv_SEMobilePhone+46709876543NationalIdentificationNumber790131-1234EndUserID12345MessageIDyour_unique_deposit_idNotificationURLURL_to_your_notification_servicePasswordmerchant_passwordUsernamemerchant_username
If there's a specific expected order, you may need to define that order in a structure or use a hard coded template in a policy.
If it's alphabetical or random, you could write some javascript to go through the json as required and build out your string
@dknezic I have tried multiple JavaScripts below but always getting Access to Java class is prohibited. Is it something wrong with the code? could you please help checking..
JS-1
var obj = context.getVariable('data');
var output = ""
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
//console.log(val);
output += key+val
walk(val);
}
}
}
walk(obj);
console.log(output)
Js-2
var obj = context.getVariable('data');
var output = ""
function iterateKeys(obj) {
if (obj && typeof obj === 'object') {
Object.keys(obj).forEach(function(key) {
//console.log(key);
//output = output + key+ obj[key]
iterateKeys(obj[key]); // recursion
});
}
}
iterateKeys(your_object)
context.setVariable("output", output)
JS-3
var obj = context.getVariable('data');
var output = ""
function iterateObject(obj) {
for (var key in obj) {
try{
var object = JSON.parse(obj[key]);
output += key + obj[key]
}
catch(e){
iterateObject(obj[key]);
}
/*if (obj[key] instanceof Object) {
iterateObject(obj[key]);
} else {
output += key + obj[key]
//console.log(key, obj[key]);
}*/
}
}
JS-4
var obj = context.getVariable('data');
function iterateKeys(obj) {
if (obj && typeof obj === 'object') {
Object.keys(obj).forEach(function(key) {
console.log(key);
iterateKeys(obj[key]); // recursion
});
}
}
iterateKeys(obj)
what is your data variable? and what's the stacktrace?