AWS Lambda Merge JSON
AWS Lambda

AWS Lambda Merge JSON

So sometimes after using a parallel state from AWS step functions, we get an array of objects from the different branches. What if we want a single output from the parallel state? Well, there’s a lambda function for that.

By taking functions off of https://github.com/jacob418/node_json-merge and turning it into a lambda function, we get this:

exports.handler = (event, context, callback) => {
var output = {};
event.forEach(function(obj) { output = mergeJSON(output, obj); });
context.succeed(output);
};

var jsonC = {}.constructor;

var isJSON = function(json) {
if (json && json.constructor === jsonC) {
return true;
} else {
return false;
}
}

var mergeJSON = function(json1, json2) {
var result = null;
if (isJSON(json2)) {
result = {};
if (isJSON(json1)) {
for (var key in json1) {
result[key] = json1[key];
}
}

for (var key in json2) {
if (typeof result[key] === “object” && typeof json2 === “object”) {
result[key] = mergeJSON(result[key], json2[key]);
} else {
result[key] = json2[key];
}
}
} else if (Array.isArray(json1) && Array.isArray(json2)) {
result = json1;

for (var i = 0; i < json2.length; i++) {
if (result.indexOf(json2[i]) === -1) {
result[result.length] = json2[i];
}
}
} else {
result = json2;
}

return result;
}

This function will make sure to merge your json objects. You have to be careful with your keys though as any same key will be overwritten by the latest merged object.

https://gist.github.com/nilesuan/76061f6b3838e99dadd2c7c91ae7338f

Previous Post

You Might Also Like

No Comments

Leave a Reply

%d bloggers like this: