0

I am using jquery.csv to parse a csv file and show the data in a table format.

my csv file data: test.csv

header1, header2, header3, header4
value1, value2, value3, value4
value1, value2, value3, value4.1,value4.2,value4.3
value1, value2, value3, value4

My code: index.html

    var data;

    $.ajax({

        type: "GET",

        url: "test.csv",

        dataType: "text",

        success: function(response) {

            data = $.csv.toObjects(reponse);

            // generating the table for user view
            generateTable(data);

        var html = generateTable(data);

        $('#result').html(html);

    }

});

function generateTable(data) {

    var html = '';

    if (typeof(data[0]) === 'undefined') {

        return null;

    }

    if (data[0].constructor === Object) {

        for (var row in data) {

            html += '<tr>\r\n';

            for (var item in data[row]) {

                html += '<td>' + item + ':' + data[row][item] + '</td>\r\n';

            }

            html += '</tr>\r\n';

        }

    }

    return html;

}

The code doesnt generate an error and it shows in the table that i print is one value per header, but I would want to know how can I get several value per header? Like for header4 there are several values and I would want all values in the cell for header4. Or if you can suggest any better way of parsing this kind of data I would appreciate it. thanx!

JSFiddle

http://jsfiddle.net/xpvt214o/685678/

rockStar
  • 1,296
  • 12
  • 22
  • Can you please attach a jsfiddle or a running demo? – Ofir Baruch Aug 27 '18 at 11:51
  • updated with the remodeled question of jsfiddle, there instead of using a file im using a textarea, but the output is the same output as what im getting with the file too. – rockStar Aug 27 '18 at 12:21

2 Answers2

2

So... Now I understood your question, hehe. Here we go:

            function generateTable(lines) {
                if (typeof(lines) === 'undefined' || lines.length == 0) {
                    return '';
                }
                var header = lines[0].split(',');
                var html = '';
                for (var row in lines) {
                    if(row == 0) {
                        continue;
                    }
                    html += '<tr>\r\n';
                    var cols = lines[row].split(',');
                    for (var col in cols) {
                        var item = header[col] ? header[col] : header[header.length-1];
                        html += '<td>' + item + ':' + cols[col] + '</td>\r\n';
                    }
                    html += '</tr>\r\n';
                }
                return html;
            }
            $.ajax({
                type: "GET",
                url: "test.csv",
                dataType: "text",
                success: function(response) {
                    $('#result').html(generateTable($.csv.parsers.splitLines(response)));
                }
            });

You can't do what you want just using the default parser. So you should create your own parser with $.csv.parsers.splitLines helper (you can read about that there). So you can do whatever you want to do with those values of overflow cases. In your case, you want to use the last "column header" as the header of those values, right? That's happening on this line:

var item = header[col] ? header[col] : header[header.length-1];

If that column exists on the header definition, it'll call the header name. If doesn't, it'll call the last header name. That's it?

Kaique Garcia
  • 528
  • 3
  • 15
  • you have hit the mark bro, thanx a bunch. btw i was thinking if it's also possible to change the separators of those overflow elements instead of comma changing them to `:` . the column numbers are static. – rockStar Aug 27 '18 at 17:26
  • 1
    @rockStar of course you can, but you'll need to map it to an array before print the result, something like: `var rows = {}` using each header name as indexes, do you get it? I can do something about this later, I'm a litle busy for now. – Kaique Garcia Aug 27 '18 at 17:28
  • 1
    I think my example isn't right... Reading it again, hehe. The mapping should result in something like this: `var rows = [{"header1": "value1", "header2": "value2", "header3": "value3", "header4": "value4:value4.1:value4.2"}];` – Kaique Garcia Aug 27 '18 at 17:33
  • 1
    yeah the mapping should be like that, thanx for taking the time in looking into my problem. I would post a question for this so it would be fair for you. :) – rockStar Aug 27 '18 at 18:16
  • i have posted the question here https://stackoverflow.com/questions/52045315/changing-commas-into-colon-after-third-consecutive-commas, i hope u can help me..thanx :) – rockStar Aug 27 '18 at 18:47
1

I checked your fiddle and made a console.log to let me print out your parsed csv object. It prints the variable without the last two items from line 3. Your problem is that the csv parser dropps these items. I think this happens due to your incorect csv.

You should add your csv like this to make it parsed correclty:

header1, header2, header3, header4,header4.2,header4.3
value1, value2, value3, value4,,
value1, value2, value3, value4.1,value4.2,value4.3
value1, value2, value3, value4,,

I think the csv-parser needs an equal amount of elements on each row.

I've tested this csv in your fiddle and it shows all elements, but add empty or undefined ones for 2nd and 4th row.

  • 1
    true, that's what i noticed too, so im thinking of a work around right now but i dont know where to start. i'll probably post a new question. thank you for your response. – rockStar Aug 27 '18 at 13:00
  • You're welcome. I would recommend to request a json file and iterate over it to build the table. – Florian de Ville Aug 27 '18 at 13:04
  • if you have a reference about this method i would be glad to read about it. – rockStar Aug 27 '18 at 13:13