从嵌套列表构建JSON输出

时间:2012-05-16 16:31:30

标签: jquery json list

我有以下无序列表:

<ul class="primary">
    <li id="1"><span>Product Family A</span>
       <ul class="secondary">
           <li><span>A.1</span></li>
           <li><span>A.2</span></li>
       </ul>
    </li>
    <li id="2"><span>Product Family B</span>
       <ul class="secondary">
           <li><span>B.1</span></li>
       </ul>
    </li>
    etc...
</ul> 

我想用jQuery生成下面的输出。有人可以帮忙吗?

product_family:[{
   id:1,
   products:[{
      model: A1,
      model: A2
}],
product_family:[{
   id:2,
   products:[{
      model: B1
}]

谢谢!

2 个答案:

答案 0 :(得分:1)

var out = [];
$('ul.primary > li').each(function(index, val) {
    out[index] = {
        product_family : this.id,
        products: []
    };
    $('ul > li', this).each(function() {
        out[index].products.push({
            model: $('span', this).text()
        });
    })
});

答案 1 :(得分:0)

请注意,此部分无效:

products:[{
    model: A1,
    model: A2
}],

我假设你打算写这个:

products:[
    { model: A1 },
    { model: A2 }
}],

您可以使用以下内容:

var pf = [];
$("ul.primary").children("li").each(function(i,e) {
    var products = [];
    $(e).find('ul').find('span').each(function(i2,e2) {
        products.push({ model: $(e2).find('ul') });
    });
    pf.push( {
        id: (i+1),
        products: products
    });
});