使用Jquery </ul>将平面Json列表解析为嵌套<ul>

时间:2010-01-14 13:37:01

标签: jquery json

我正在尝试将一个扁平的Json对象渲染到像&lt; ul&gt;这样的树中。使用jquery。

这是Json对象的样子

[
    {"FacetTypeId":1,"ProductId":22,"FacetName":"Gender","FacetSysName":"Gender","FacetTypeName":"Mens","FacetTypeSysName":"Mens"},
    {"FacetTypeId":6,"ProductId":22,"FacetName":"Size","FacetSysName":"Size","FacetTypeName":"157","FacetTypeSysName":"157"},
    {"FacetTypeId":7,"ProductId":22,"FacetName":"Size","FacetSysName":"Size","FacetTypeName":"158","FacetTypeSysName":"158"},
    {"FacetTypeId":15,"ProductId":22,"FacetName":"Size","FacetSysName":"Year","FacetTypeName":"2008","FacetTypeSysName":"2008"}
]

我想像这样创建一个嵌套的ul:

<ul>
    <li>
        Gender
        <ul>
            <li>Mens</li>
        </ul>       
    </li>
    <li>
        Size
        <ul>
            <li>157</li>
            <li>158</li>
        </ul>       
    </li>
    <li>
        Year
        <ul>
            <li>2008</li>           
        </ul>       
    </li>
</ul>

有人可以帮助指出可以实现的最好方法吗?

1 个答案:

答案 0 :(得分:3)

您可以使用json.org中提供的JSON解析器来解析您的字符串,如下所示:

function parseJSON(s) {
    return JSON.parse(s, function (key, value) {
        var type;
        if (value && typeof value === 'object') {
            type = value.type;
            if (typeof type === 'string' && typeof window[type] === 'function') {
                return new (window[type])(value);
            }
        }
        return value;
    });
}

var arr = parseJSON(yourStringHere);

// Build object structure with FacetSysName as key
var categories = { }, current, cat;
for (var i = 0; i < arr.length; i++) {
    current = arr[i];
    cat = current.FacetSysName;
    categories[cat] = categories[cat] || [];
    categories[cat].push(current.FacetTypeName);
}

// Build ul element and append to body
var ulOuter = $('<ul></ul>'), ulInner, li, items;
for (cat in categories) {
    li = $('<li>' + cat + '</li>').appendTo(ulOuter);
    items = categories[cat];
    ulInner = $('<ul></ul>').appendTo(li);;
    for (var i = 0; i < items.length; i++) {
        ulInner.append($('<li>' + items[i] + '</li>'));
    }
}

$(body).append(ulOuter);