S
S
septim5042020-12-10 21:55:54
JSON
septim504, 2020-12-10 21:55:54

How to convert json to html table?

Hello. I have code

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
    var data = [
  {
    "UserID": 1,
    "UserName": "rooter",
    "Password": "12345",
    "Country": "UK",
    "Email": "[email protected]"
  },
  {
    "UserID": 2,
    "UserName": "binu",
    "Password": "123",
    "Country": "uk",
    "Email": "[email protected]"
  },
  {
    "UserID": 3,
    "UserName": "cal",
    "Password": "123",
    "Country": "uk",
    "Email": "[email protected]"
  },
  {
    "UserID": 4,
    "UserName": "nera",
    "Password": "1234",
    "Country": "uk",
    "Email": "[email protected]"
  }
];
$(document).ready(function () {
    var html = '<table class="table table-striped">';
    html += '<tr>';
    var flag = 0;
    $.each(data[0], function(index, value){
        html += '<th>'+index+'</th>';
    });
    html += '</tr>';
     $.each(data, function(index, value){
         html += '<tr>';
        $.each(value, function(index2, value2){
            html += '<td>'+value2+'</td>';
        });
        html += '<tr>';
     });
     html += '</table>';
     $('body').html(html);
});

which works well, but instead of var data = [...] I need the data from my json file, which is located in the same place as the script and is called test.json . How can I write the path correctly? No matter how much I tried, nothing happened.5fd26f1b69f99848731454.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Reality, 2020-12-10
@septim504

$.getJSON("test.json", function(json){
        data = json;
}

Somehow it should work like this :) The rest of the script needs to be placed inside this construction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question