I'm trying to flatten any type of json object with unlimited embedded levels from something like this:
[
{
"one": 1,
"two": 2,
"three": [
{
"four": 4,
"five": 5
},
{
"six": 6,
"seven": 7
}
]
},
{
"one": 1,
"two": 2
}
]
into something like this (desired result):
{
"0": {
"prefix[0]one": 1,
"prefix[0]three[0]five": 5,
"prefix[0]three[0]four": 4,
"prefix[0]three[1]seven": 7,
"prefix[0]three[1]six": 6,
"prefix[0]two": 2
},
"1": {
"prefix[1]one": 1,
"prefix[1]two": 2
}
}
Now I have found a script that works very well as far as flattening the data (good starting point), but I am trying to figure out how to tweak the code so that it groups each top level array/object into it's own array/object rather than one large single object like the script does on that page (see accepted answer "JSON.flatten").
Here is the cleanest version I have so far to achieve the desired result which is not much different from the original. I have tried much more than this but its too sloppy to post.
JSON.flatten = function(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(data, "prefix");
return result;
}
Here's what the current code produces:
{
"prefix[0]one": 1,
"prefix[0]three[0]five": 5,
"prefix[0]three[0]four": 4,
"prefix[0]three[1]seven": 7,
"prefix[0]three[1]six": 6,
"prefix[0]two": 2,
"prefix[1]one": 1,
"prefix[1]two": 2
}
Note: I do not necessarily need to use the sample code provided. Any code that achieves the desired result will do.
Thanks All!
UPDATE:
I've realized my desired output was needing to be something more like so:
{
"0": {
"prefix[0][one]": 1,
"prefix[0][three][0][five]": 5,
"prefix[0][three][0][four]": 4,
"prefix[0][three][1][seven]": 7,
"prefix[0][three][1][six]": 6,
"prefix[0][two]": 2
},
"1": {
"prefix[1][one]": 1,
"prefix[1][two]": 2
}
}
But even after getting it to format like that using CViejo's suggestions I ended up finding out that this would not work entirely because of the nested objects. They would have had to been objects as well down to an unlimited level. So I'm taking Tomalak's suggestion and trying out the recurse approach and assign values as I go. I just wanted to thank both you guys for providing some great suggestions!