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;
}
When using the JSON library that Daff talked about you douls imply do the following:
If you want to create a JSON string of the following format {id: html, id: html}, you could do this:
(for refrence, this is the JSON library mentioned by Daff: http://code.google.com/p/jquery-json/)