Convert JSON data into a nested unordered list

I need help converting a JSON object into an unordered list using jQuery. Here's the JSON data I have:

var myJSON = "{name:\"Director\",children:[name:\"Exe Director1\",name:\"Exe Director2\",name:\"Exe Director3\",children:[name:\"Sub Director1\",name:\"Sub Director2\",name:\"Sub Director3\",children:[name:\"Cameraman 1\",name:\"Cameraman 2\"]]]}";

The desired output is as follows:

<ul>
    <li>Director
        <ul>
            <li>Exe Director 1</li>
            <li>Exe Director 2</li>
            <li>Exe Director 3
                <ul>
                    <li>Sub Director 1</li>
                    <li>Sub Director 2</li>
                    <li>Sub Director 3
                        <ul>
                            <li>Cameraman 1</li>
                            <li>Cameraman 2</li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I'm not sure how to approach this, so any guidance would be greatly appreciated!

Thank you,

Answer №1

Here's the solution you need:

You can use the jQuery template API, which was previously a part of jQuery but is now only available as a plugin. However, it's likely that jQuery will reintroduce this or a similar technique in the near future.

To get started, visit http://api.jquery.com/category/plugins/templates/.

The usage of the API is incredibly easy. Simply follow this syntax:

$.tmpl("template", jsonObject)

Let me give you a basic example using a small template:

$.tmpl(
    "<li><b>${Id}</b>${Name}</li>", 
    [{Id:1, Name:"Werner"}, {Id:2, Name:"Klaus"}]
);

In this case, the output would be a jQuery HTML element that can be appended anywhere on your webpage:

  • 1 Werner
  • 2 Klaus
  • If your data is more complex, don't worry! You can easily iterate through JSON sub objects by using the "{{each}}" template notation. Here's an example illustrating how to structure your data and template for such cases:

    var data = {name:"Director",children:[{name:"Exe Director1"},{name:"Exe Director2"},{name:"Exe Director3", children:[{name:"Sub Director3_1"},{name:"Sub Director3_2"},{name:"Sub Director3_3",children:[{name:"Cameraman3_3_1"},{name:"Cameraman3_3_2"}]}]}]};
    
    var template = '\
        <ul>\
            <li>${name}\
                <ul>\
                    {{each(childindex, child) children}}\
                        <li>${child.name}\
                            <ul>\
                                {{each(child2index, child2) child.children}}\
                                    <li>${child2.name}</li>\
                                {{/each}}\
                            </ul>\
                        </li>\
                    {{/each}}\
                </ul>\
            </li>\
        </ul>\
    ';
    
    $('body').empty().append($.tmpl(template, data));
    

    The result in browsers would be:

    • Director
      • Exe Director1
      • Exe Director2
      • Exe Director3
        • Sub Director3_1
        • Sub Director3_2
        • Sub Director3_3
        • ...

    If you want to support full recursion, you can further enhance this solution by including nested templates. However, I'll leave that as an exercise for you.

    Cheers, Will

    Answer №2

    A unique way to achieve this is by using a recursive function that generates an HTML menu structure for given data. Each time the function is called, it creates "UL" and "LI" elements.

    function generateMenu(data) {
    
        var ul = $("<ul>");
    
            $(data).each(function (i, dir) {
                 var li = $('<li>' + dir.name + '</li>');
                 ul.append(li);
    
                if (dir.children != null && dir.children.length > 0) {
                    li.append(generateMenu(dir.children));
                }
    
            });
    
        return ul;
    };
    

    To utilize this function, you can simply append the generated menu to a specified element with the following code:

    $("#some-div").append(generateMenu(myJsonData));

    In order to generate the desired menu, the data should be in JSON format. Here's an example of how the JSON data should look like:

    var myJsonData = JSON.parse('{"name": "Director","children": [{ "name": "Exe Director1" },{ "name": "Exe Director2" },{"name": "Exe Director3","children": [{ "name": "Sub Director1" },{ "name": "Sub Director2" },{"name": "Sub Director3","children": [{ "name": "Cameraman 1" },{ "name": "Cameraman 2" }]}]}]}');

    Similar questions

    If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

    How to position collapsible buttons in Twitter's Bootstrap framework

    I have successfully created two buttons on the same line. The second button is collapsible and when clicked, it adds a row of two more buttons to the view. However, the newly collapsed row of buttons appears aligned with the second button. I would like th ...

    What is the smoothest way to animate price changes as you scroll?

    After searching online, I could only find a version for swift. The only keyword that resulted in a search was ScrollCounter. Is it possible to create this type of animation using CSS and HTML? If anyone knows of a helpful resource or example, please share ...

    Input form with multiple fields. Automatically display or hide labels based on whether each field is populated or empty

    I am attempting to create a form where the placeholders move to the top of the input when it is focused or filled. However, I have encountered an issue with having multiple inputs on the same page. Currently, my JavaScript code affects all inputs on the pa ...

    Sneaky spam and ads embedded within Joomla template

    Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

    Updating the CSS link href in ASP.NET using code behind

    I'm struggling with changing the CSS href in the code-behind of my .ASPX page. I've tried various methods but haven't found a solution that works as intended. HTML Markup: <link id="linkCSS" runat="server" href='/css/1.css' re ...

    Do iframes not utilize parental jquery?

    I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functions ...

    Utilize JSON categories to assign groups to TextFields or Selects according to a JSON data attribute

    I have retrieved multiple JSON groups from an API, each containing one or more questions objects. My goal is to display each question along with its corresponding response in a MUI TextField or Select component, based on the value of QuestionType. Current ...

    Guide to integrating search feature with json and Ajax

    I am diving into the world of JSON and AJAX with a thirst for knowledge. My goal is to create a search function that is case insensitive and can easily append results to a table. However, I seem to be facing some issues with the code I have written. HTM ...

    Error Alert: React Native object cannot be used as a React child within JSON, leading to an Invariant Violation

    When using React-Native: To start, here is the example code of a json file: Any placeholders marked with "..." are for string values that are not relevant to the question. [ { "id": "question1" "label": "..." "option": [ { "order": 1, "name": "..."}, ...

    IE6 disrupts stored layouts

    I've encountered a strange issue with my design in IE6. It loads perfectly at first, but after reloading it a couple of times, everything suddenly collapses. The strange part is that when I upload an updated version, it fixes the issue, only to break ...

    Querying Mongodb with extended millisecond intervals

    I have a collection that I need to export every 5 minutes based on the timestamp field. When querying the collection, the maximum date is as follows: db.testcol.find({},{_id : 0,ts : 1}).sort({ts:-1}) 2017-04-14 23:40:27.690Z I converted it to mil ...

    Despite receiving a return false from the Ajax verification, the form is still submitted when using onsubmit

    I have implemented form verification using ajax to check for duplicate usernames. If a duplicate username is found, the function returns false; otherwise, it returns true. Below is the ajax code: function checkform(){ var username = $("#username").va ...

    Executing JavaScript code within ASP.NET Visual Basic

    My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

    What is the process for turning off tooltips and implementing an information window into amMap?

    I've developed an amMap to display areas, and I'm looking for a way to turn off the tooltip and instead show an infowindow when a specific state is clicked. Any suggestions on how to accomplish this? ...

    Having trouble parsing PHP JSON encoded data in JavaScript

    When I make an AJAX call to a PHP script that returns a JSON encoded object, I encounter some issues. $.post("php/getCamera.php", { cam_id: identifier }, function(data){ console.log(data); //var camera = JSON.parse( ...

    What could be causing the incorrect display of updates when my Grails checkbox onclick remote function Ajax call is triggered

    Hi, I have a page named taskReminder that renders two templates: one for tasks and another for reminders. The task template includes a checkbox that, when checked, should update the task list. Everything is functioning correctly, but there seems to be an i ...

    Develop a custom dropdown menu using JavaScript

    I've been working on creating a dropdown menu that appears after selecting an option from another dropdown menu. Here's the HTML code I'm using: <br> <select id ="select-container" onchange="addSelect('select-container') ...

    Displaying a visual representation of time remaining with a countdown progress bar

    While browsing online, I stumbled upon a creative progress bar code featured on this particular website. My goal is to implement a countdown timer that displays the remaining minutes and seconds rather than a percentage. In order to achieve this, I have i ...

    Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

    I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

    Delete items within the first 10 minutes of shutting it down

    Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...