jQuery树遍历-将无序列表元素嵌套到JSON

jQuery树遍历-将无序列表元素嵌套到JSON,jquery,json,tree,list,traversal,Jquery,Json,Tree,List,Traversal,好的,现在我这里有一个无序的列表: <ul id="mycustomid"> <li><a href="url of Item A" title="sometitle">Item A</a> <ul class="children"> <li><a href="url of Child

好的,现在我这里有一个无序的列表:

<ul id="mycustomid">
    <li><a href="url of Item A" title="sometitle">Item A</a>
        <ul class="children">
           <li><a href="url of Child1 of A" title="sometitle">Child1 of A</a>
               <ul class="children">
                 <li><a href="url of Grandchild of A" title="sometitle">Grandchild of A</a>
                    <ul class="children">
                       <li><a href="url of Grand Grand child of A" title="sometitle">Grand Grand child of A</a></li>
                    </ul>
                </li>
               </ul>
           </li>
        </ul>
    </li>
    <li><a href="url of Item B" title="sometitle">Item B</a></li>
    <li><a href="url of Item C" title="sometitle">Item C</a></li>
</ul>
一些有用的参考资料:

Javascript解决方案:

^这一个可能有效,但我需要的JSON输出格式如上所示,而不是此脚本输出的格式:(

其他参考资料:

{
        name: "Item A",
        url: "url of Item A",
        title: "sometitle",
        children: [{
                   name: "Child1 of A",
                   url: "url of Child1 of A",
                   title: "sometitle",
                   children: [{
                                name: "Grandchild of A",
                                url: "url of Grandchild of A",
                                title: "sometitle",
                                children: [{
                                           name: "Grand Grand child of A",
                                           url: "url of Grand Grand child of A",
                                           title: "sometitle",
                                           children: []
                                           }]
                              }]
                   }]
},
           {
            name: "Item B",
            url: "url of Item B",
            title: "sometitle",
            children: []
           },
           {
            name: "Item C",
            url: "url of Item C",
            title: "sometitle",
            children: []
           }

有人请帮忙:(

很多个不眠之夜我都在绞尽脑汁……(P.s-我花了40多分钟来编写整个页面和代码)

啊,一个有趣的小递归练习。我花了一点时间来做这件事,下面是我将如何做的。这是一个多层递归的工作,但假设您的数据不够深,无法爆炸内存(浏览器中的递归如果太深就会中断)。至少可以达到10级左右

我测试了这个,似乎它的工作,只要保存在一个HTML文件,你应该是好的

很抱歉,没有太多的评论(从技术上讲,一点也没有:),这假设您阅读jQuery和JS代码都很好。如果您有问题,请发表评论,我很乐意解释

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title>Recursive list processor example</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">

$(document).ready(function() {

    var out = [];

    function processOneLi(node) {       

        var aNode = node.children("a:first");
        var retVal = {
            "title": aNode.attr("title"),
            "url": aNode.attr("href"),
            "name": aNode.text()
        };

        node.find("> .children > li").each(function() {
            if (!retVal.hasOwnProperty("children")) {
                retVal.children = [];
            }
            retVal.children.push(processOneLi($(this)));
        });

        return retVal;
    }

    $("#mycustomid").children("li").each(function() {
        out.push(processOneLi($(this)));
    });


    console.log("got the following JSON from your HTML:", JSON.stringify(out));

});

    </script>
</head>
<body>
<ul id="mycustomid">
    <li><a href="http://example.com/urlOfItemA" title="sometitle">Item A</a>
        <ul class="children">
           <li><a href="http://example.com/urlOfItemAChild1" title="sometitle">Child1 of A</a>
               <ul class="children">
                 <li><a href="http://example.com/urlOfItemAGrandchild" title="sometitle">Grandchild of A</a>
                    <ul class="children">
                       <li><a href="http://example.com/urlOfItemAGrandGrandChild" title="sometitle">Grand Grand child of A</a></li>
                    </ul>
                </li>
               </ul>
           </li>
        </ul>
    </li>
    <li><a href="http://example.com/urlOfItemB" title="sometitle2">Item '"" B</a></li>
    <li><a href="http://example.com/urlOfItemC" title="sometitle3">Item C</a></li>
</ul>
</body>
</html>

递归列表处理器示例
$(文档).ready(函数(){
var out=[];
函数processOneLi(节点){
var阳极=node.children(“a:first”);
变量retVal={
“标题”:阳极属性(“标题”),
“url”:aNode.attr(“href”),
“名称”:阳极。文本()
};
node.find(“>.children>li”).each(function(){
如果(!retVal.hasOwnProperty(“子项”)){
retVal.children=[];
}
retVal.children.push(processOneLi($(this));
});
返回返回;
}
$(“#mycustomid”).children(“li”).each(function(){
push(processOneLi($(this));
});
log(“从HTML中获得以下JSON:”,JSON.stringify(out));
});

似乎是一种递归解决方案,使用一个函数处理列表元素(子元素)集合,一个函数处理列表元素。注意,我假设您希望将其格式化为字符串,并且它实际上表示为数组

$(function() {
    var json = formatListElements( $('#mycustomid > li') );
});

function formatListElements( elems )
{
    var contents = [] 
    $.each( elems, function( index, elem ) {
        contents[index] = formatListElement( elem );
    }
    return '[' + contents.join(', ') + ']';
}

function formatListElement( elem )
{
   var anchor = $(elem).children('a:first');
   return '{ "name": "' + quote( anchor.text() )
                + '", "url": "' + quote( anchor.attr('href') )
                + '", "title": "' + quote( anchor.attr('title') )
                + '", "children": ' + formatListElements( $(elem).find('> ul > li')
        + '}';
}

function quote( str )
{
    return str.replace( /"/g, '\\\"' );
}

下面的源代码是我的解决方案。我认为已经足够清楚地展示了将ul转换为json对象的原理。。祝你好运:)

$(函数(){
函数buildJSON($li){
var subObj={“name”:$li.contents().eq(0.text().trim()};
$li.children('ul').children()。每个(函数(){
如果(!subObj.children){subObj.children=[];}
push(buildJSON($(this));
});
返回子对象;
}
var obj=buildJSON($(“#ul data”).children();
$('body').append('').find('pre').append(JSON.stringify(obj,null,2));
});


正在处理它。顺便说一句,生成的JSON是一个对象数组,因此您应该有周围的[和]括号。
[{},{},{},{}]
谢谢Samuel,但我的应用程序似乎使用了无效的JSON,并且它使用了上述格式:)谢谢您的输入:)这会输出无效的JSON,因为:1)您没有引用属性值2)您没有转义“或”“字符串中的字符,可以引用属性值。否则就好了。@Jaanus——是的,只是一个简单的回答,完全没有经过测试。我已经在属性周围添加了引号,并在字符串中引用了引号。按照您现在的做法,您可能会得到太多的引号。。不确定是否必须在JSON“blah”blah“字符串中引用“:)@Jaanus——可能是对的,只需要引用双引号。不过我认为这不会有什么坏处。@tv-我检查了JSON标准和Doug Crockford的JSON字符串发生器。JSON标准明确谈到双引号,因此双引号是唯一需要在字符串中转义的,而不是单引号。这会很痛,因为输出中会有额外的反斜杠字符。对不起,Jaanus,我不在办公桌上。非常感谢您的努力,您提供的代码非常完美,您是我伪装的祝福,您为我省去了很多麻烦!!非常感谢!!!:)您还应该标记接受的答案,无论您接受哪个,都是一个好的Stackoverflow公民:)但是,它不会以我的格式输出JSON吗?例如,我在属性上有引号,例如:“name”:“something”“title”:“something”,而我需要它像name:“something”title:“something”谢谢JSON标准规定对象键必须用双引号引起来。我使用的是Douglas Crockford的标准JSON输出程序,它是将Javascript对象转换为JSON字符串的行业标准。因此,您需要的是非标准的无效JSON。你为什么需要它?1)别担心,我们都是新来的:)2)我明白你的意思。JSON等标准的要点是,应用程序以标准方式输入和输出JSON。正确的做法是修复应用程序,使其接受标准有效的JSON。如果这是不可能的,您可以让tvanfonsson的代码工作。您可以看到它是如何将自定义JSON输出为字符串的,您可以对其进行修改以生成所需的内容。但事实上,你应该修复另一个应用程序。还有其他的方法,但它们都是非常糟糕的做法。