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;
};
0

2 Answers 2

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(':')));
Sign up to request clarification or add additional context in comments.

2 Comments

Either works, though I think a recursive solution would likely be more readable.
It reminds me of a line from a textbook. "Every recursion problem can be solved with loops but not viceversa." +1 for simple solution
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.