1

I have a JSON file with data in a structure like that:

{
    "first": {
        "second": "example",
        "third": {
            "fourth": "example2",
            "fifth": "example3"
        }
    }
}

Is there a way to convert it to a flat structure to get only name-value pairs with a string value? From this JSON i want to get something like this:

{
"second": "example",
"fourth": "example2",
"fifth": "example3"
}
user2340612
  • 10,053
  • 4
  • 41
  • 66
deviant
  • 127
  • 1
  • 1
  • 7
  • 3
    @deviant have a look at this: http://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects – Peter Szekeli Feb 26 '16 at 07:53

2 Answers2

2

This might give you some idea in pure JavaScript how to flatten your object. It's quite crude, but can be expanded:

function flatten(obj) {
    var flattened = {};

    for (var prop in obj)
        if (obj.hasOwnProperty(prop)) {
            //If it's an object, and not an array, then enter recursively (reduction case).
            if (typeof obj[prop] === 'object' && 
                Object.prototype.toString.call(obj[prop]) !== '[object Array]') {
                var child = flatten(obj[prop]);

                for (var p in child)
                   if (child.hasOwnProperty(p))
                       flattened[p] = child[p];
            }
            //Otherwise if it's a string, add to our flattened object (base case).
            else if (typeof obj[prop] === 'string')
                flattened[prop] = obj[prop];
        }

    return flattened;
}

fiddle

lintmouse
  • 5,079
  • 8
  • 38
  • 54
2

It can be done by recursive function:

var obj = {
"first": {
    "second": "example",
    "third": {
        "fourth": "example2",
        "fifth": "example3"
    }
}
};


function parseObj(_object) {
    var tmp = {};
    $.each(_object, function(k, v) {
  if(typeof v == 'object') {
    tmp = $.extend({}, tmp, parseObj(v));
  } else {
    tmp[k] = v; 
  }

});
    return tmp;
}

var objParsed = {};
objParsed = parseObj(obj);
console.log(objParsed);

Here is working JSFiddle: https://jsfiddle.net/0ohbyu7b/

Sojtin
  • 2,714
  • 2
  • 18
  • 32