Hi,
I have a requirement to convert the incoming json payload field names from camel case(testCase) to snake case (test_case) using javascript in apigee.
this logic to be applicable only for field names which are in camel case. if the field name is already in snake case. then no conversion required.
Please help with js logic.
Thanks in advance.
answered elsewhere.
reposting here.
// camelCaseToSnakeCase.js
// ------------------------------------------------------------------
//
// created: Thu Jul 18 08:08:11 2024
// last saved: <2024-July-18 08:19:20>
var camelCasePattern = new RegExp("^([a-z]+)([A-Z][a-z]+)");
function camelCaseToSnakeCase(propname) {
var m1;
while ((m1 = camelCasePattern.exec(propname))) {
propname = m1[1] + "_" + m1[2].charAt(0).toLowerCase() + m1[2].slice(1);
}
return propname;
}
function convertPropertyNames(obj, converterFn) {
var r,
value,
t = Object.prototype.toString.apply(obj);
if (t == "[object Object]") {
r = {};
for (var propname in obj) {
value = obj[propname];
r[converterFn(propname)] = convertPropertyNames(value, converterFn);
}
return r;
} else if (t == "[object Array]") {
r = [];
for (var i = 0, L = obj.length; i < L; ++i) {
value = obj[i];
r[i] = convertPropertyNames(value, converterFn);
}
return r;
}
return obj;
}
// a test
var originalObject = {
isSuccess: true,
responseDate: "2019-02-20T11:42:11.963Z",
result: {
recordCount: "abc123",
billDetailsList: [
{
sourceSystem: "Abc123",
billAmount: "Abc123",
billCreationDate: "2019-02-19T09:16:04Z"
},
{
sourceSystem: "abc123",
billAmount: "XyzAbc",
billCreationDate: "abc123"
}
]
}
};
var converted = convertPropertyNames(originalObject, camelCaseToSnakeCase);
print(JSON.stringify(converted, null, 2) + "\n");
// add your context.getVariable() and context.setVariable() as appropriate.
Hi @Annapurna! If the answer you received worked, please mark it as solved to help others. We appreciate your engagement!