Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert the items of an LI into a json object using jquery?

Tags:

json

html

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 that into a json object like so:

[{"id":"1","title":"Bob"}, {"id":"2","title":"Frank"}, {"id":"3","title":"Frank"}]

I need to get that data into that format so I can then pass pass it in a $.post() call back to my php server.

Can someone tell me how to get the items from that list and convert them into the above json using jQuery?

like image 386
Mithrax Avatar asked Dec 03 '09 03:12

Mithrax


People also ask

What is toJSON () in JSON?

toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.


1 Answers

jQuery actually has something built-in for building the array: map()

var items = $('.nameList').find('li').map(function() {
  var item = { };

  item.id = this.value;
  item.title = $(this).text();

  return item;
});

That will build an array of objects matching the JSON structure you're after. Then, to JSON serialize that, use JSON.stringify which is built into newer browsers and available for older ones by including json2.js:

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

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

like image 158
Dave Ward Avatar answered Sep 20 '22 09:09

Dave Ward