-1

I have an unordered list and some li elements under the ul. I can not get the ul and li value as I expect. I tried several resources as below:

http://jsfiddle.net/mohammadwali/tkhb5/

how-do-i-convert-the-items-of-an-li-into-a-json-object-using-jquery

jquery-tree-traversal-nested-unordered-list-elements-to-json

My code is here as below in the fiddle:

My code is in this fiddle

My expected output is as below:

[{
    "id": "1",
    "category": "Parking",
    "subcategory": [
        "Street Parking",
        "Bus Parking"
    ]
}]

How can I achieve the JSON?

Antti29
  • 2,953
  • 12
  • 34
  • 36
  • I researced a lot, But why down vote? – RidwanulHaque Oct 08 '17 at 08:26
  • 1
    I did not down-voted, but I suppose apart from adding links if you could add your code snippet here as well question would look more complete. Instead of pasting bunch of links. – warl0ck Oct 08 '17 at 09:31

2 Answers2

1

Try this:
Please note that I've changed the html a bit by adding a data-name to the top li elements.

var mylist = [];
$(".nameList > li").each(function() {
    mylist.push({});
  var self = mylist[mylist.length-1];
  self.subcategory = [];
  self.id = $(this).attr("value");
  self.category = $(this).attr("data-name");
  $(this).find("ul > li").each(function(){
    self.subcategory.push($(this).html());
  });
  console.log(self);
});

And here's a fiddle:
http://jsfiddle.net/tkhb5/262/

Nir Tzezana
  • 2,275
  • 3
  • 33
  • 56
1

If you can't touch the HTML, here you have an option...

var myList = [];

$('ul.nameList > li').each(function() {
    myList.push({
        "id": $(this).val(),
        "category": $(this).clone().children('ul.subcatList').remove().end().text().trim(),
        "subcategory": $(this).find('ul.subcatList li').toArray().map(function(value) { return value.innerHTML; })
    });
});

... but if you can, I will put the category name in some element, to make easier to select it. You could use...

<li value="1"><span class="cattitle">Parking</span>
  <ul class="subcatList">
    <li>Street Parking</li>
    <li>Bus Parking</li>
    <li>Complementary Parking</li>
  </ul>
</li>
<li value="2"><span class="cattitle">Business Services</span>
  <ul class="subcatList">
    <li>Business Center</li>
    <li>A/V Capabilities</li>
    <li>Video Conferencing</li>
  </ul>
</li>
........

... so you can simplify the jQuery...

var myList = [];

$('ul.nameList > li').each(function() {
    myList.push({
        "id": $(this).val(),
        "category": $(this).children('span.classtitle').text(),
        "subcategory": $(this).find('ul.subcatList li').toArray().map(function(value) { return value.innerHTML; })
    });
});

I hope it helps

A. Iglesias
  • 2,625
  • 2
  • 8
  • 23