Jack
Jack

Reputation: 275

Print key and values from dictionary to html table (in a certain format) JSON call

The code below is a JSON call which grabs a dict and prints out keys and values to a html table

$(function() {
      $('a#search').bind('click', function() {
        $.getJSON('/_search', {
          a: $('input[name="a"]').val()
        }, function(data) {
          var tableData = '<table>'
          $.each(data.result, function(key, value){
            tableData += '<tr>' + key + ' ' + '</tr>';
            $.each(value, function(val){
                tableData += '<td>' + val + '</td>';
              });
          });
          tableData += '</table>';
          $('#table').html(tableData);
        });
        return false;
      });
    });

however this prints as follows

Developer Publisher ReleaseDate Title
0         1         2
0         1         2
0         1         2
0         1         2

it should be printing like this

Developer Publisher ReleaseDate Title
0         0         0           0
1         1         1           1
2         2         2           2

and I dont know why its missing the contents inside and printing just 0 1 2 so in the end it should print like this

Developer      Publisher ReleaseDate Title
Office Kouan   Shouei    ...         ...
Jorudan        Vap       ...         ...
Beam Software  ...       ...         ...

any idea to what might be wrong?

Upvotes: 1

Views: 1311

Answers (1)

seekers01
seekers01

Reputation: 560

Please change the code to :

$(function () {
    $('a#search').bind('click', function () {
        $.getJSON('/_search', {
            a: $('input[name="a"]').val()
        }, function (data) {
            var tableData = '<table>'
            $.each(data.result, function (key, value) {
                tableData += '<tr>' + key + ' ' + '</tr>';
                $.each(value, function (val) {
                    tableData += '<td>' + value[val] + '</td>';
                });
            });
            tableData += '</table>';
            $('#table').html(tableData);
        });
        return false;
    });
});

calling val in your code is just printing the index not the actual value inside your javascript object, hence using value[val].

Hope this helps. Cheers .. :)

Upvotes: 1

Related Questions