2
\$\begingroup\$

Intro -> I have to convert an excel file, which comes usually in this way:

enter image description here

to a Json file that must looks like this:

"DE": {
   "Title":"Title_DE",
   "Subtitle":"Subtitle_DE",
   "Title_2":"Title_2_DE",
   "Subtitle_2":"Subtitle_2_DE"
}
"GR": {
   "Title":"Title_GR",
   "Subtitle":"Subtitle_GR",
   "Title_2":"Title_2_GR",
   "Subtitle_2":"Subtitle_2_GR"
}
"EN": {
   "Title":"Title_EN",
   "Subtitle":"Subtitle_EN",
   "Title_2":"Title_2_EN",
   "Subtitle_2":"Subtitle_2_EN"
}

What I've done -> I have used this node module xlsx to parse the excel file. The code currently works but something in my mind tells me that was not the best way to do it or at least there was a clearest or a smartest way.

const XLSX = require('xlsx');
const fs = require('fs');
let workbook = XLSX.readFile('./src/xls/test.xlsx'); 
let sheet_name_list = workbook.SheetNames; //--> sheet names
let isocodes = [];
let labels = [];
let copy = [];
let obj = {};
let j = 0;

sheet_name_list.map(sheet => { //--> sheet names loop
    let worksheet = workbook.Sheets[sheet]; 
    for (index in worksheet) {
        let idCol = index.substring(1, 3);
        let idRow = index.substring(0, 1);
        if (idCol === "1") {
            isocodes.push((worksheet[index].v).trim()); //--> isocodes
        }
        if (idRow === "A") {
            labels.push((worksheet[index].v).trim()); //--> labels
        }
        if (idRow != "A" && idCol != "1") {
            copy.push(worksheet[index].v); //--> copy
        }
    }
});

isocodes.shift(); //--> delete undefined
labels.shift();
copy.shift();

isocodes.map(iso => { //--> create object to convert
    obj[iso] = {};
    for (let i = 0; i < labels.length; i++) {
        obj[iso][labels[i]] = copy[(i * isocodes.length) + j];
    }
    j++;
});
//--> write json files in their folder
fs.writeFile('src/lang/desktop.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("desktop json file created"));
fs.writeFile('src/lang/mobile.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("mobile json file created"));

Please share your thoughts!!!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.