microarm15
microarm15

Reputation: 171

Generate HTML code from data stored in csv, xml or json

What I have: a csv (can be converted to xml or maybe to json) file that has many rows, each row contains several columns that store data about some profile.

What I need to do: to generate an html page that corresponds to each row automatically given the html elements' layout. Since I may have hundreds of rows and all pages got identical html elements (I mean, like an imdb or facebook profile) except the unique profile data shown to users, a small change to the layout of a page later would require days of stupid manual work.

Is there some kind of framework that can do what I seek to do? Thank you!

Upvotes: 1

Views: 2149

Answers (2)

John Slegers
John Slegers

Reputation: 47101

The process

You need three steps :

1) Use Ajax to fetch data from your server and turn it into an array. You could do this eg. with the following jQuery :

$.ajax({
    type: "GET",
    url: "data.csv",
    success: CSVToHTMLTable
});

2) Once you have get your file, you need to parse it. Json and XML support are native in JavaScript. An easy & reliable way to do it for a CSV file, would be to use a library like Papa Parse :

var data = Papa.parse(data).data;

3) You need to define a function to transform your array into an HTML table. Here's how you could do this with jQuery :

function arrayToTable(tableData) {
    var table = $('<table></table>');
    $(tableData).each(function (i, rowData) {
        var row = $('<tr></tr>');
        $(rowData).each(function (j, cellData) {
            row.append($('<td>'+cellData+'</td>'));
        });
        table.append(row);
    });
    return table;
}

Putting everything together

Here's how you can put everything together :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>
<script>
    function arrayToTable(tableData) {
        var table = $('<table></table>');
        $(tableData).each(function (i, rowData) {
            var row = $('<tr></tr>');
            $(rowData).each(function (j, cellData) {
                row.append($('<td>'+cellData+'</td>'));
            });
            table.append(row);
        });
        return table;
    }

    $.ajax({
        type: "GET",
        url: "http://localhost/test/data.csv",
        success: function (data) {
            $('body').append(arrayToTable(Papa.parse(data).data));
        }
    });
</script>

Upvotes: 3

Marc Dix
Marc Dix

Reputation: 1969

I'd suggest json2html if you can convert your csv to json.

Upvotes: 0

Related Questions