tags:

views:

43

answers:

2

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;
    }
+1  A: 

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.

Daff
A: 

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/)

Pim Jager
That library throws an "Out of stack space" when I try to do to Json on simple ul li
epitka
I misunderstood how to actually use it. Your code helped. Thanks
epitka