Your question is not quite clear, so I have to guess... Do you want to put all the values that follow of: into an array? So basically one could write the original input with indents as follows (with every indent signifying a new array)?
here
is
an:example
of:
how:this:works:
foo:bar
example
Besides, your second JSON example is not correct, the content of the of: array would have to be wrapped in braces since arrays can't have keys.
Well, assuming you wanted to have the result I described above, you could quite easily do this with recursion:
var jsonify = function(input) {
var helper = function(items) {
var end = [];
for (i = 0; i < items.length; ++i) {
var itemparts = items[i].split(':');
var value = itemparts.pop();
var dobreak = false;
while (itemparts.length) {
var obj = {};
if (value == "" && i+1 < items.length) {
// Recursive call
value = helper(items.slice(i+1,items.length));
dobreak = true;
}
obj[itemparts.pop()] = value;
value = obj;
}
end.push(value);
if (dobreak) {
break;
}
}
return end;
};
return helper(input.split('\r\n'));
};
This function searches for zero length values and checks if there are values in the following lines. If so, all the values that follow (items.slice(...)) are processed separately with the same function (i.e. recursively) to put them into an array.
When calling jsonify with the example input above, you'll get the following JSON:
[
"here",
"is",
{
"an": "example"
},
{
"of": [
{
"how": {
"this": {
"works": [
{
"foo": "bar"
},
"example"
]
}
}
}
]
}
]
Hope that helps... ;)