I have this JSON array
// Json array
var productList = {\"products\": [
{\"description\": \"product 1\", \"price\": \"9.99\"},
{\"description\": \"pr
Since you're already using jQuery, why don't you use the $.each() function?
Instead of this code:
var listItem = document.createElement('li');
listItem.setAttribute('id', 'listitem');
listItem.innerHTML = productList.products[0].description;
$(list).append(listItem);
Use this:
$(productList.products).each(function(index){
$(list).append('<li id="listitem">' + this.description + " = " + this.price + '</li>');
});
Check out jQuery.each()
$.each(productList.products, function(index, value) {
$(list).append('<li>' + value.description + ': ' + value.price + '</li>');
});
Using the "JSON array" or better named JavaScript object described below you can loop through it using for loops. productlist is an object that contains an array and each element in this array is an object that contains 2 properties or variables (description and price). The array can be iterated though using a typical for loop starting at 0 and ending at the array lenght - 1....the objects inside each array element can be iterated through using the "for (key in object)" notation.
// Json array
var productList = {"products": [
{"description": "product 1", "price": "9.99"},
{"description": "product 2", "price": "9.99"},
{"description": "product 3", "price": "9.99"}
]
};
Here is an example of iterating through your Javascript Object.
for (var i = 0; i < productList.products.length; i ++) {
for (var key in productList.products) {
alert(key + ":" + productList.products[key]);
}
}
I appears to me that what you really need is the .tmpl
plugin to build your list from your json data:
http://api.jquery.com/jquery.tmpl/