L.hawes
L.hawes

Reputation: 199

Convert dynamic JSON array to HTML

I have a Django view that will return JSON data depending on what is given to it. Each JSON element will have the same fields but the returned JSON array will have a dynamic amount of elements.

Here is an example of the possible JSON data that could be returned:

[
   {
      "Open Job Lines": 0,
      "Open Hours": 0,
      "Repair Order": "123454",
      "Expected Pay": 1.9,
      "Actual Pay": 1.0,
      "Pay Status": "Underpaid"
   }
]

Here is an example or a JSON return with multiple elements:

[
   {
      "Open Job Lines": 0,
      "Open Hours": 0,
      "Repair Order": "123454",
      "Expected Pay": 1.9,
      "Actual Pay": 1.0,
      "Pay Status": "Underpaid"
   },
   {
      "Open Job Lines": 0,
      "Open Hours": 0,
      "Repair Order": "123454",
      "Expected Pay": 1.9,
      "Actual Pay": 1.0,
      "Pay Status": "Underpaid"
    }
]

Using JavaScript, I would like to turn this into HTML similar to following and assign it to a variable.

Open Job Lines: 0 <br>
Open Hours: 0 <br>
Repair Order: 123454 <br>
Expected Pay: 1.9 <br>
Actual Pay: 1.0 <br>
Pay Status: Underpaid <br>

Open Job Lines: 0, <br>
Open Hours: 0 <br>
Repair Order: 123454 <br>
Expected Pay: 1.9 <br>
Actual Pay: 1.0 <br>
Pay Status": Underpaid <br>

Upvotes: 0

Views: 245

Answers (1)

Oscar Jara
Oscar Jara

Reputation: 14187

Is this what you need?

Because you question is not that clear.

$(document).ready(function() {

  // Let's assume your data was already returned from the AJAX call...
  var data = [{
      "Open Job Lines": 0,
      "Open Hours": 0,
      "Repair Order": "123454",
      "Expected Pay": 1.9,
      "Actual Pay": 1.0,
      "Pay Status": "Underpaid"
  }, {
      "Open Job Lines": 0,
      "Open Hours": 0,
      "Repair Order": "123454",
      "Expected Pay": 1.9,
      "Actual Pay": 1.0,
      "Pay Status": "Underpaid"
  }];

  displayHTML(data, $('#output'));

});

/**
 * Used to build and display the HTML from a specific set of data.
 * @param {Object[]} - An array of objects containing the data to be processed.
 * @param {Object} - A jQuery object with the element where the HTML will be displayed.
 */
function displayHTML(data, outputEl) {
  $.each(data, function(index, record) {
    for (var property in record) {
      if (record.hasOwnProperty(property)) {
        outputEl.append('<b>' + property + '</b>: ' + record[property] + '<br>');
      }
    }
    outputEl.append('<br>');
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

Upvotes: 1

Related Questions