Tabulator - CSV to JSON

138 Views Asked by At

I would like to know if there will be a way to transform a csv to the JSON format suitable for the Tabulator library?

The idea would be to have a format as seen on excel : - the first cell on the top left, empty - columns A, B, C... AA, AB... according to the number of cells on the longest row - the line number automatically on the first cell of each line)

I had the idea of doing it directly with loops, but it takes a lot of time I find. I don't see any other way.

Thank you for the help.

1

There are 1 best solutions below

0
On BEST ANSWER

Check the following function, I hope this is what you are looking for...

let csvfile = 'title1,title2,title3,title4\n1,2,3,4\n11,22,33,44' //YOUR CSV FILE
let capLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' // ALPHABET SET
let finalJson = [];
let headers;
let line =[];

convertCSV2JSON(csvfile)

function convertCSV2JSON(csv) {
    line = csv.split("\n"); //PARSE ALL AVAILABLE LINES INTO ARRAY
    result = [];
    
    headers = line[0].split(","); //PARSE ALL AVAILABLE STRING NAMES INTO ARRAY AND KEEP ONLY THE FIRST ONE (HEADER)

  
    line.slice(1).forEach(function(item,i){ //RUN EACH ITEM EXCLUDING COLUMN NAMES
        var obj = {};

        if(line[i] === null || line[i] === undefined) {
        }else{

                var entries = line[i+1].split(","); // SEPARATE FOUND ENTRIES EXCLUDING COLUMN NAMES (i+1)

                for(var j = 0; j < entries.length; j++) { // PARSE ENTRIES 
                        obj[convert2Letters(j)] = entries[j]; // ASSIGN A LETTER AS COLUMN NAME
                }
        }
        finalJson.push(obj);
    })
    console.log(finalJson);
}

function convert2Letters(iteration) {
    let readyLetter = ''
    while (iteration >= 0) {
    
        readyLetter += capLetters[iteration % 26]
        iteration = Math.floor(iteration / 26) - 1
    }
    return readyLetter
}

The fuzzy part was at foreach() function, because you cannot initiate index at your preference... slice() did the trick!

Moreover convert2Letters() function takes an array of letters and on each iteration finds the modulus of 26 letters, removing by one shows you the next combination...

Example:

  • If you have 30 columns it will give 30 % 26 = 4
  • 4 corresponds to capLetters[4] which is 'E'
  • calculate next: iteration = Math.floor(iteration / 26) - 1 which means on every 26 increment (0,26,52,78...) it will give (-1,0,1,2...) corresponding. So a 30 columns iteration will have 0 as result which corresponds to capLetters[0] = 'A'
  • Resulting: 30 columns will give letters 'EA'