user8954059
user8954059

Reputation: 9

Convert json to html table output in javascript/JQuery

I get the JSON output on the UI using the below function

$("#idvar").click(function(){
  var d1 = document.getElementById("dText");
  var d2 = document.getElementById("dJson");
  var mytext = d1.textContent;
  alert(mytext);
  $.post(
    url,
    {doc: mytext},
    function(data) {
      console.log(Object.keys(data).length);
      d2.textContent = data;
    }
  );
});

where d1 is the displaying the uploaded input document, d2 for the output generated from processing the document on a model. Currently, I am getting json format. I tried to implement the codes in these posts (Parsing JSON objects for HTML table, Convert json data to a html table), but I get [object, Object] in the text area. Is there a way to convert the json to table.

In the URL text area i get

 [{"tag":"a1","relevance":0.5},
  {"tag":"a2","relevance":0.3},
  {"tag":"c3","relevance":0.2},{"tag":"d3,
   ...

Instead, I was hoping to get

enter image description here

Upvotes: 0

Views: 895

Answers (1)

Piyin
Piyin

Reputation: 1834

You should traverse the data and print it in table format. First, make sure the element with id dJson is a <table> element. Then, you can change your success callback to something like:

function(data) {
  console.log(Object.keys(data).length);
  var html = '<tr><th>Tag</th><th>Relevance</th></tr>';
  for(var i=0; i<data.length; i++){
    html +=
      '<tr>' +
        '<td>' +
          data[i].tag +
        '</td>' +
        '<td>' +
          data[i].relevance +
        '</td>' +
      '</tr>'
    ;
  }
  d2.innerHTML = html;
}

Here you have a working example (without the $.post call): https://jsfiddle.net/cLbqmwa4/

Upvotes: 1

Related Questions