Change UL to a JSON format

I am attempting to transform an entire unordered list (UL) and its child elements into a JSON object.

Here is the approach we took:

function extractData(element) {
    element.find('li').each(function () {
        data.push({ "name": $(this).find('span').html(), "position": $(this).find('strong').html() });
    });
}

JS Fiddle showcasing the code: https://jsfiddle.net/cbzo0ef2/2/

However, all elements are on the same level. In this scenario, it's necessary to maintain all levels accordingly.

Answer №1

$(this).parents("ul").length is a clever solution to consider:

function fetchData(element) {
    element.find('li').each(function () {
        data.push({ "name": $(this).find('span').html(), "position": $(this).find('strong').html(), "departmentLevel": $(this).parents("ul").length  })
    });
  }

Additional effort is required to incorporate department level into your json structure

Check out this example for reference

Answer №2

Here is a JavaScript solution that extracts data from HTML elements while maintaining the structure:

(function($) {

    function getData(el) {
        var data = [];

        el.children('li').each(function () {
            var currentElement = $(this);

            var nomeElement = currentElement.children('span')[0];
            var cargoElement = currentElement.children('strong')[0];

            var item = {};

            if (nomeElement && cargoElement) {
                item.nome = $(nomeElement).html();
                item.cargo = $(cargoElement).html();
            }

            data.push(item);

            var child = currentElement.children('ul')[0];

            if (child != null) {
                item.children = getData($(child));
            }
        });

        return data;
    }

    var data = getData($('.root'));
    console.log(data);

})(jQuery);

You can view this code in action on JSFiddle: https://jsfiddle.net/52t58551/

Answer №3

By using the jQuery Children method and implementing recursion, it is possible to retrieve every node.

(function($) {
  function fetchData(element) {
    var currentData = [];
    element.children('li, ul').each(function(index, childElement) {
      currentData.push({
        nodeName: childElement.nodeName,
        name: $(childElement).find("> span").text(),
        position: $(childElement).find("> strong").text(),
        subLevelData: fetchData($(childElement))
      });
    });
    return currentData
  }

  var finalResult = fetchData($('.root'));
  console.log(JSON.stringify(finalResult));

})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="root"> <li><span>a</span><strong>b</strong></li><li><span>c</span><strong>d</strong></li><li><span>e</span><strong>f</strong></li><li> <ul> <li><span>g</span><strong>h</strong></li><li><span>i</span><strong>j</strong></li><li> <ul> <li><span>k</span><strong>l</strong></li></ul> </li></ul> </li></ul>

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

Failed to transmit data to the CouchDB database

When attempting to execute this code for sending data to my CouchDB database, I encountered the following error: 2015-06-04 15:30:43.426 ddd[8303:640525] requestReply: {"error":"bad_request","reason":"Referer header required."} Is there a way to resolv ...

What is the process for deserializing a JSON-wrapped collection property into a generic class

The Challenge Many APIs that return RESTful JSON data wrap collections within an object. This object typically includes a property indicating the number of items in the collection. Consider the following examples: { "animals": [ {"name": "Ra ...

js The correct value is not being set to the div's style.top

function gamestart(){ var gr; var gr = true; console.log(gr==true); if(gr == true){ console.log("we have activated pointer key detection dear Mr.ketsebaot") document.onkeydown = checkk; } } function checkk(e){ cons ...

FrisbyJS and JSONSchema encounter a SchemaError when the specified schema does not exist

I utilize frisbyjs along with modules like jsonschema and jasmine-node for execution. There is a particular schema named test.json: { "error": { "type": "array", "minItems": 2, "items": { "type": "object", "properties": { ...

Creating a repository of essential functions in AngularJSDiscover the steps to set up a

I am looking to create a set of reusable functions in AngularJS for CRUD operations that can be used across multiple entities in my project. I have already set up a factory using $resource for server communication, which looks like this: Model File: var ...

Showing Json information using ajax in Codeigniter 4

Although I can see my JSON data in the browser console, I am unable to display it in the template. <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: '<?php echo_uri("clients/session_ ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

Troubleshooting jQuery Ajax issues in a modularized environment

Having trouble getting this function to work properly. It's being called from a separate .js file. function TabLoaderAJAX(xurl, xdata) { var result = null; $.ajax({ type: 'POST', url: '/services/TabLoader.asmx/& ...

Tips for displaying identical tab content across various tabs using jquery or javascript

For instance, if we have tabs labeled as 1, 2, 3, 4, and 5, and a user has selected tabs 2, 3, and 4, how can we display the same content for those tabs while showing different content for the remaining ones? ...

Tips for chaining actions in Javascript using ActionSequence, LegacyActionSequence, or a similar method

I encountered an error while attempting to execute this example, despite trying both ActionSequence and LegacyActionSequence. I am in search of the correct method to chain actions. My attempts to find a solution in resources such as https://seleniumhq.git ...

Discovering the key within a complicated JSON file using C# and the Newtonsoft library

{ "items": [ { "_id": { "$oid": "5968dd23fc13ae04d9000001" }, "item_name": "sildenafil citrate", "supplier": "Wisozk Inc", "quantity": 261, "unit_cost": "$1 ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Having an issue with receiving an "undefined variable" error message when trying to validate a form using PHP and AJAX

Upon loading my page, an error message appears: Notice: Undefined variable: titleErr in index.php on line 141 I have already initialized the $titleErr variable at the start of my PHP code, what could be causing this issue? PHP: <?php $titleE ...

Combining these two statements in jQuery: What's the best way to do it?

if($(this).parents("ul").closest("#menu-main").length){ var parent = $(this).parent(); parent.addClass("current"); if(parent.hasClass("more-options")){ $(parent).siblings(".more-options-page").addClass("current").show(); } } Instead of redun ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

How to implement multiple dependent select boxes in Rails?

I'm currently working on developing a car application where each car is assigned to a specific make and model. However, not all makes have every model available. My goal is to create a series of select boxes that update dynamically based on the selec ...

Tips for managing the onblur event using selenium automation framework

I want to trigger an onblur event when I click away using JavaScript. I tried the following code: ((JavascriptExecutor)getDriverProvider().executeScript("document.getElementByXpath('xpath here').onblur();"); However, it doesn't seem to wo ...

Utilizing Ajax for populating a cascading selection menu

Currently, I am in the process of dynamically changing the options in a drop-down list using ajax and jquery by fetching data from a database. With jquery, I can easily clear and add new options to the drop-down. However, my issue arises when attempting to ...