jQuery:将层次结构序列化为Json [英] jQuery: serializing hierarchical structure to Json

查看:95
本文介绍了jQuery:将层次结构序列化为Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个嵌套的无序列表,我想序列化为json.使用jQuery的最佳方法是什么?

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;
    }

推荐答案

在使用Daff谈到的douls JSON库时,请执行以下操作:

When using the JSON library that Daff talked about you douls imply do the following:

$.toJSON($("ul#someUL li"));

如果您要创建以下格式的{{id:html,id:html}} JSON字符串,可以执行以下操作:

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

(为方便起见,这是Daff提到的JSON库: http://code .google.com/p/jquery-json/)

(for refrence, this is the JSON library mentioned by Daff: http://code.google.com/p/jquery-json/)

这篇关于jQuery:将层次结构序列化为Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆