• Bob
  • How to convert LI elements to json object using jquery?

    If I have a list like the following:

    <ul class="nameList"> <li value="1">Bob</li> <li value="2">Frank</li> <li value="3">Sally</li> </ul> 

    How can I convert this to a json object, for example:

    [{"ID": "1", "name": "Bob"}, {"ID": "2", "name": "Frank"}, {"ID": "3", "name": "Frank"}]

    I need to get this data in this format, then transfer it in the $ .post () image to my php server.

    Can someone tell me how to get the elements from this list and convert them to the above json using jQuery?

    +7
    json jquery html
    source share
    4 answers

    JQuery has something built-in to build an array: map ()

     var items = $('.nameList').find('li').map(function() { var item = { }; item.id = this.value; item.title = $(this).text(); return item; }); 

    This will build an array of objects matching the JSON structure you are using. Then, for JSON to serialize this, use JSON.stringify, which is built into new browsers and is available for older ones, including json2.js :

     // Produces [{'id':1,'title':'bob'},{etc},{etc}] var json = JSON.stringify(items); 

    Also keep in mind that $ .post () automatically serializes the data parameter of the object, since key1 = value1 & key2 = value2 & etc. Unless you really need JSON on the server side, the JSON serialization step may not be necessary.

    +10
    source share
     var items = []; $('ul.nameList').children().each(function() { var $this = $(this); var item = { id: $this.attr('value'), title: $this.html() }; items.push(item); }); 
    +6
    source share


    You can just click them on the JSON object. Here's how -

      // create a blank array var mylist = []; // loop trough the li $("ul.nameList > li").each(function () { //push element data to the array mylist.push({ "id": $(this).attr("value"), "title": $(this).text() }); }) // then you can simply pass it to the post method $.post("myhandler.php", { list: mylist }, function (data) { // recived data }) 

    And of course your html

     <ul class="nameList"> <li value="1">Bob</li> <li value="2">Frank</li> <li value="3">Sally</li> </ul> 

    Working example - http://jsfiddle.net/mohammadwali/tkhb5/

    Hope this helps!

    +4
    source share
    +2
    source share

    All Articles