Skip to content

Instantly share code, notes, and snippets.

@subhashdasyam
Last active April 14, 2019 17:20
Show Gist options
  • Save subhashdasyam/f50ae90f3599d14407d2b7e8f18b465c to your computer and use it in GitHub Desktop.
Save subhashdasyam/f50ae90f3599d14407d2b7e8f18b465c to your computer and use it in GitHub Desktop.
Unordered List to Json
# HTML FILE
<div id="res">
</div>
# JAVASCRIPT
var j = '[{"parent":"Hello","children":{}},{"parent":"Hai","children":{}},{"parent":true,"children":{"0":"School1","1":"School2"}},{"parent":"Test","children":{}}]';
var obj = $.parseJSON(j);
var x = "";
$.each(obj, function(index, value) {
x += '<li>'+value.parent+'</li>';
if(value.children[0]){
var s = '<ul>'
$.each(value.children, function(i, v) {
s += "<li>"+v+"</li>";
});
s += '</ul>'
x += s;
}
});
$("#res").html("<ul=\"ul\">"+x+"</ul>");
<ul id="ul">
<li>Hello</li>
<li>Hai</li>
<li> H
<ul>
<li>School1</li>
<li>School2</li>
</ul>
</li>
<li>Test</li>
</ul>
var result = [];
function getList(element) {
$.each($(element).children('li'), function() {
var target = $(this),
index = target.index(this) + 1,
data = $(target).text().indexOf("\n") !== -1 || $(target).text(),
eachObj = {};
eachObj.parent = data;
if(target.has('ul')) {
var aff = {};
var c = 0;
$.each($('ul li', target), function() {
aff[c] = $(this).text();
c++;
});
}
eachObj.children = aff;
result.push(eachObj)
});
return result;
}
console.log(JSON.stringify(getList($('ul#ul'))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment