UNPKG

@woosh/dream-tools-localization

Version:

Localization tooling for DREAM engine

71 lines (49 loc) 1.98 kB
import XLSX from 'xlsx'; /** * Convert Excel spreadsheet to individual JSON files * designed to work in conjunction with Localization package of DREAM engine * @param {Buffer} file * @param {number} [worksheet_index] * @returns {{json:Object, name:string }[]} name is the name of locale, taken from first row of the XLS */ export function parse_localization_XLS_to_JSON({ file, worksheet_index = 0 }) { /* Call XLSX */ const workbook = XLSX.read(file, { type: "buffer" }); const sheet = workbook.Sheets[workbook.SheetNames[worksheet_index]]; const sheet_json = XLSX.utils.sheet_to_json(sheet, { raw: false, header: 1 }); const headerRow = sheet_json[0]; const languages = headerRow.slice(1); const rowCount = sheet_json.length; const result = []; for (let i = 0; i < languages.length; i++) { const language = languages[i]; //generate a key-value file var json = {}; for (let k = 1; k < rowCount; k++) { const row = sheet_json[k]; const key = row[0]; const value = row[i + 1]; if (value === undefined) { //no value continue; } //replace special characters const formattedValue = value.replace(/\&\#([a-fA-F0-9]+)\;/gi, function (match, code) { return String.fromCharCode(code); }); if (json.hasOwnProperty(key)) { if (json[key] !== formattedValue) { //re-definition console.error(`duplicate key definition:'${key}', old value='${json[key]}', new value='${value}', keeping old value`); } continue; } json[key] = formattedValue; } result.push({ name: language, json: json }); } return result; }