简体   繁体   中英

Javascript Recursion for creating a JSON object

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

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(':')));

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM