JSON to HTML TABLE Converter in Javascript

Following JSON formats are converted in above converter tool:

Format 1:

[
    {"key": "value 1", "col": "row 1"},
    {"key": "value 2", "col": "row 2"}
]

Format 2:

{ "Products" : [
  {    "id":1,    "p_name":"Product 1"  },
  {    "id":2,    "p_name":"Product 2"  },
  {    "id":3,    "p_name":"Product 3"  },
  {    "id":4,    "p_name":"Product 4"  }
] }

Format 3:

{
    "key 1": "value 1", "key 2": "value 2", "key 3": "value 3", "key 4": "value 4"
}

How to Convert JSON format to HTML Table format:

  • Copy paste json data in textbox OR upload JSON data file
  • Output will shown in result section.

SOURCE CODE:

HTML Code

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="row">
    <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
        <div class="form-group">
            <label>Enter JSON Data:</label>
            <textarea id="jsondata" rows="5" class="form-control"></textarea>
        </div>
    </div>
    <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
        <label>Upload JSON file:</label>
        <div class="item-wrapper one">
            <div class="item">
                <form action="jsontohtml.php" method="post" enctype="multipart/form-data">
                    <div class="item-inner">
                        <div class="item-content">
                            <div class="image-upload">
                                <label style="cursor: pointer;" for="file_upload">
                                    <div class="h-100">
                                        <div class="dplay-tbl">
                                            <div class="dplay-tbl-cell">
                                                <i class="fa fa-cloud-upload"></i>
                                                <h5><b>Choose Your file to Upload</b></h5>
                                                <h6 class="mt-10 mb-70">Or Drop Your File Here</h6>
                                            </div>
                                        </div>
                                    </div>
                                    <input accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" name="excelfile" id="file_upload" class="image-input" required>
                                </label>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<div class="form-group">
    <label>Result:</label>
    <textarea id="result" class="prettyprint form-control" rows="10"></textarea>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

Javascript Code:

$(document).ready(function() {
    $("#jsondata").keyup(function() {
        json = JSON.parse($("#jsondata").val());
        
        let result = "<table class=\"table\">";
        if (Array.isArray(json)) {
            result += getDataFromArray(json);    
        } else {
            let keys = Object.keys(json);
            if (Array.isArray(json[keys[0]])) {
                let jsonData = json[keys[0]];
                result += getDataFromArray(jsonData);
            } else {
                result += getTableHeader(keys);
                result += getTableData(keys, json);
            }
        }
        result += "</table>";
        var beautify_html = html_beautify(result);
        document.querySelector("#result").value = beautify_html;
        
    });
    
    $("#file_upload").change(function() {
        if(document.querySelector('#file_upload').files.length == 0) {
            alert('Error : No file selected');
            return;
        }
        var file = document.querySelector('#file_upload').files[0];
        
        if(file.size > 2*1024*1024) {
            alert('Error : Exceeded size 2MB');
            return;
        }
        
        var file = $('#file_upload').get(0).files[0];
        var reader = new FileReader();
        reader.onload = function (e) {
            //get the file result, split by comma to remove the prefix, then base64 decode the contents
            var decodedText = atob(e.target.result.split(',')[1]);
            json = JSON.parse(decodedText);
            //show the file contents
            let result = "<table class=\"table\">";
            if (Array.isArray(json)) {
                result += getDataFromArray(json);    
            } else {
                let keys = Object.keys(json);
                if (Array.isArray(json[keys[0]])) {
                    let jsonData = json[keys[0]];
                    result += getDataFromArray(jsonData);
                } else {
                    result += getTableHeader(keys);
                    result += getTableData(keys, json);
                }
            }
            result += "</table>";
            var beautify_html = html_beautify(result);
            document.querySelector("#result").value = beautify_html;
        };
        reader.readAsDataURL(file);
    });
});

function getTableHeader(keys) {
    let tblhead = "<tr>";
    for (let i = 0; i < keys.length; i++) {
        tblhead += "<th>"+ keys[i] +"</th>";
    }
    tblhead += "</tr>";
    return tblhead;
}

function getTableData(keys, json) {
    let tbldata = "<tr>";
    for (let i = 0; i < keys.length; i++) {
        let value = json[keys[i]];
        if (value != undefined) {
            tbldata += "<td>"+ value +"</td>";
        } else {
            tbldata += "<td></td>";
        }
    }
    tbldata += "</tr>";
    return tbldata;
}

function getDataFromArray(json) {
    let header = Array();
    let keys = Object.keys(json);
    for (let i = 0; i < keys.length; i++) {
        let temp = json[i];
        let temp1 = Object.keys(temp);
        for(let z = 0; z < temp1.length; z++) {
            if (header.indexOf(temp1[z]) == -1) {
                header.push(temp1[z]);
            }
        }
    }

    let data = "";
    data += getTableHeader(header);
    for (let i = 0; i < keys.length; i++) {
        let temp = json[i];
        data += getTableData(header, temp);
    }
    return data;
}