3

needing some advice on how to do this properly recursively.

Basically what I'm doing, is entering in a bunch of text and it returns it as JSON.

For example:

The text:

q
b
name:rawr

Returns:

[
  "q",
  "b",
  {
    "name": "rawr"
  }
]

And the following input:

q
b
name:rawr:awesome

Would return (output format is not important):

[
  "q",
  "b",
  {
    "name": {
        "rawr": "awesome"
    }
  }
]

How can I modify the following code to allow a recursive way to have objects in objects.

var jsonify = function(input){
  var listItems = input, myArray = [], end = [], i, item;

  var items = listItems.split('\r\n');

  // Loop through all the items
  for(i = 0; i < items.length; i++){

    item = items[i].split(':');

    // If there is a value, then split it to create an object
    if(item[1] !== undefined){
      var obj = {};
      obj[item[0]] = item[1];  
      end.push(obj);
    }
    else{
      end.push(item[0]);
    }
  }

  // return the results
  return end;
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Menztrual
  • 40,867
  • 12
  • 57
  • 70

2 Answers2

7

I don't think recursion is the right approach here, a loop could do that as well:

var itemparts = items[i].split(':');

var value = itemparts.pop();
while (itemparts.length) {
    var obj = {};
    obj[itemparts.pop()] = value;
    value = obj;
}
end.push(value);

Of course, as recursion and loops have equivalent might, you can do the same with a recursive function:

function recurse(parts) {
    if (parts.length == 1)
        return parts[0];
    // else
    var obj = {};
    obj[parts.shift()] = recurse(parts);
    return obj;
}
end.push(recurse(items[i].split(':')));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

Here is a solution with recursion:

var data = [];

function createJSON(input) {

    var rows = input.split("\n");
    for(var i = 0; i < rows.length; i++) {
        data.push(createObject(rows[i].split(":")));
        }

    }

function createObject(array) {
    if(array.length === 1) {
        return array[0];
        } else {
        var obj = {};
        obj[array[0]] = createObject(array.splice(1));
        return obj;
        }
    }

createJSON("p\nq\nname:rawr:awesome");
console.log(data);
Amberlamps
  • 39,180
  • 5
  • 43
  • 53