Javascript recursion to create a JSON object

need some tips on how to do this correctly recursively.

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

For example:

Text:

q b name:rawr 

Return:

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

And the following input:

 q b name:rawr:awesome 

Will 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; }; 
+1
javascript
source share
2 answers

I don’t think that recursion is the right approach, a loop can also do:

 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, since recursion and loops have an equivalent capability, 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(':'))); 
+6
source share

Here is the recursion solution:

 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); 
+2
source share

All Articles