If I have a list like the following:
- Bob
- Frank
-
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.