1

I'm trying to render a flat Json obect into a tree like <ul> using jquery.

This is what the Json object looks like

[
    {"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"}
]

I'd like to create a nested ul like this:

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

Can anyone help point out the best way this could be achieved please?

2
  • I'd probably write some code... that would do it. Commented Jan 14, 2010 at 13:44
  • thanks for the extremely helpful answer Lazarus... Commented Jan 14, 2010 at 13:47

1 Answer 1

3

You could use the JSON parser available from json.org to parse your string like this:

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.