Display all elements in json array

I am trying to work with json and I almost have what I need. I get the correct information to display, but I need to pass each element of the array to a variable, and then print the variable. I would like to display all the elements in each array. The json data I work with is an invoice application ( www.curdbee.com ) and I am trying to show every invoice to a customer. The data I want to show is each position, the price of the position, and the total amount. Here is my code:

$(document).ready(function() { $.getJSON('https://nspirelab.curdbee.com/invoices.json?api_token=__token__', function(data){ $.each(data, function(index, item){ var total = item.invoice.total_billed; var lineItemName1 = item.invoice.line_items[0].name_and_description; var lineItemName2 = item.invoice.line_items[1].name_and_description; var lineItemPrice1 = item.invoice.line_items[0].price; var lineItemPrice2 = item.invoice.line_items[1].price; $('#results').append('<div class="lineItem"><ul><li>' + lineItemName1 + lineItemPrice1 + '</li><li>' + lineItemName2 + lineItemPrice2 + '</li><li>' + total + '</li></ul></div>'); }); }); }); 
+7
source share
3 answers

The nested loop (or in jQuery, the nested $.each() ) will do the job:

 $.getJSON('https://nspirelab.curdbee.com/invoices.json?api_token=&client=104929', function(data){ $.each(data, function(index, item){ // create an empty ul (initially disconnected from the DOM) var $ul = $("<ul/>"); // iterate over the line items $.each(item.invoice.line_items, function(i, lineItem) { // create an li element with the line details and append // it to the ul $ul.append( $("<li/>").html(lineItem.name_and_description + lineItem.price) ); }); // add the totals to the end of the ul $ul.append( $("<li/>").html(item.invoice.total_billed) ); // create a new div, append the ul to it, and append the div to results $('#results').append( $('<div class="lineItem"/>').append($ul) ); }); }); 
+5
source

There are an absurd amount of libraries to facilitate such things. Do a search on “javascript templates” to see what you were missing and to find out about the various libraries that you can choose for this.

0
source

If I understand your question correctly, I think that what you are looking for is some kind of iteration mechanisms, try underscore.js .

0
source

All Articles