Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Last active June 10, 2021 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DinoChiesa/1c0111e513b3bc3d74107e6ae46c0689 to your computer and use it in GitHub Desktop.
Save DinoChiesa/1c0111e513b3bc3d74107e6ae46c0689 to your computer and use it in GitHub Desktop.
Shred JSON into context variables
// extractJsonToContextVars.js
// ------------------------------------------------------------------
//
// For a JSON payload, set context vars for all fields.
//
/* global context, properties */
var what = Object.prototype.toString;
function walkObj(obj, path, fn) {
var wo = what.call(obj), p;
path = path || '';
if (wo == "[object Object]") {
Object.keys(obj).forEach(function(key){
var item = obj[key], w = what.call(item);
var pathelts = path.split('.');
pathelts.push(key);
var newpath = pathelts.join('.');
if (w == "[object Object]" || w == "[object Array]") {
walkObj(item, newpath, fn);
}
else {
fn(newpath, item);
}
});
}
else if (wo == "[object Array]") {
obj.forEach(function(item, ix){
var w = what.call(item);
var pathelts = path.split('.');
pathelts.push('['+ix+']');
var newpath = pathelts.join('.');
if (w == "[object Object]" || w == "[object Array]") {
walkObj(item, newpath, fn);
}
else {
fn(newpath, item);
}
});
}
else {
var msg = "Unknown object to convert: " + wo + "("+ JSON.stringify(obj, null, 2).slice(0, 34) +")";
//console.log(msg);
throw {error: true, message: msg };
}
}
var sourceVariable = properties.source || 'message.content';
var outputVarPrefix = properties['output-prefix'] || 'json';
try {
var obj = JSON.parse(context.getVariable(sourceVariable));
walkObj(obj,
outputVarPrefix,
function(name, value) {
context.setVariable(name, value);
});
}
catch (e) {
context.setVariable(outputVarPrefix + '.error', "bad inbound message");
context.setVariable(outputVarPrefix + '.exception', e.toString());
}
<Javascript name='JS-ShredJSON' timeLimit='200' >
<Properties>
<Property name='output-prefix'>private</Property>
<Property name='source'>ContextVariableContainingJSON</Property>
</Properties>
<ResourceURL>jsc://extractJsonToContextVars.js</ResourceURL>
</Javascript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment