jQuery: serializing hierarchical structure to Json
Let's say I ha开发者_开发问答ve 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:
$.toJSON($("ul#someUL li"));
If you want to create a JSON string of the following format {id: html, id: html}, you could do this:
var JSONobj = {};
$("ul#someUL li").each(function(){
$t = $(this);
JSONobj[$t.attr('id')] = $t.html();
});
var JSON = $.toJSON(JSONobj);
(for refrence, this is the JSON library mentioned by Daff: http://code.google.com/p/jquery-json/)
jQuery doesn't have native publicly accessible support for JSON serialization (yet). The best approach would be to use one of the JavaScript libraries listed on JSON.org. There is a jQuery JSON project on Google Code as well.
精彩评论