Skip to content

Instantly share code, notes, and snippets.

@ihommani
Last active November 13, 2017 19:51
Show Gist options
  • Select an option

  • Save ihommani/079262ffd246c96e37c1e7ef2b4b5a11 to your computer and use it in GitHub Desktop.

Select an option

Save ihommani/079262ffd246c96e37c1e7ef2b4b5a11 to your computer and use it in GitHub Desktop.
Flatten a json
function json_structure_test(){
var json = {
'toto':{
'titi':{
'tata': 'Hello World',
'lala': 'lulu'
}
},
'cucu':'coco'};
var json2 = {
'toto': 'tata',
'titi': 'tutu',
'lala': {
'lili':'lele',
"lol":"luz",
"roro":{'gigi':'lppl'}
}
}
var flattened = flattenJson_(json2, {}, undefined, 0);
Logger.log(flattened);
if(flattened['toto'] != 'tata' || flattened['titi'] != 'tutu'){
throw new ExectionException("Problem");
}
if(flattened['lala.lili'] != 'lele'){
throw new ExectionException("Problem");
}
if(flattened['lala.lol'] != 'luz'){
throw new ExectionException("Problem");
}
if(flattened['lala.roro.gigi'] != 'lppl'){
throw new ExectionException("Problem");
}
}
/**
* Flatten the json according the following model:
*
* {
'toto': 'tata',
'titi': 'tutu',
'lala': {
'lili':'lele',
"lol":"luz",
"roro":{'gigi':'lppl'}
}
}
*
* gives
*
* {toto=tata, lala.lol=luz, lala.roro.gigi=lppl, titi=tutu, lala.lili=lele}
*
*
* @param inputJson Json to flatten
* @param outputJson Object bucket where to accumulate new entry/value pairs
* @param localTable inner var
* @param depth recursivity depth
* @returns The flatenned json
* @private
*/
function flattenJson_(inputJson, outputJson, localTable, depth) {
// we are in a json final node
if (inputJson !== null && typeof inputJson !== 'object') {
var finalTable = localTable.slice(); // we need to shallow copy the array to not modify other references
var level = finalTable.join(SEPARATOR); // constant separator
outputJson[level] = inputJson;
}
for (var key in inputJson) {
if (depth == 0) { // first key
var line = [key];
flattenJson_(inputJson[key], outputJson, line, depth + 1);
} else { // we agregate the current path element in the localtable that will contain all the path in the end.
var table = localTable.slice();
table.push(key);
flattenJson_(inputJson[key], outputJson, table, depth + 1);
}
}
return outputJson;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment