Let's say I have a nested unordered list that I would like to serialize to json. What is the best approach to this using jQuery?
Here is the solution if anybody needs it:
$(document).ready(function() {
var root = $('#root');
var jsonObj = {};
jsonObj["root"] = processNode(root);
var JSON = $.toJSON(jsonObj);
$('body').append(JSON);
alert(JSON);
});
function processNode(el) {
if (el[0] == undefined) return jsonObj;
var jsonObj = {};
jsonObj["id"] = el.attr('id') || "";
jsonObj["text"] = el.attr('text') || "";
var children = new Array();
el.children().each(function(idx) {
children.push(processNode($(this)));
});
jsonObj["children"] = children;
return jsonObj;
}