使用JavaScript生成JSON时本地化字符串损坏的问题求助
本地化字符串输出损坏问题排查与修复
问题背景
我有两个对象,一个存储英文字符串值,另一个存储对应本地化值。localeGenerator.js代码如下:
/*English Strings/* const filteredKeys = { "Select a connection" : "Select a connection", "Script Viewer" : "Script Viewer", "Execution Script" : "Execution Script", "Workflows" : "Workflows", "Select Workflow" : "Select Workflow", }; /*localized value with respect to English string*/ const translations = { "Saved Actions": "Actions enregistrées", "Select a connection": "Sélectionner une connexion", "Execution Script": "Exécution Script", "Close": "Fermer", "Workflows": "Workflows", "Select Workflow": "Sélectionner un workflow", "Clone": "Cloner" }; let outputFileJson = {}; let notFoundTranslatedValues = []; for (element in filteredKeys) { if (element in filteredKeys) { if (translations[element] === undefined) notFoundTranslatedValues.push(element); outputFileJson[element] = translations[element]; } else { notFoundTranslatedValues.push(element); } }
执行命令 node .\localeGenerator.js > outputResult 生成outputResult JSON文件后,发现本地化字符串损坏,求解决办法。
修复方案
1. 缺失JSON输出逻辑
当前代码仅构建了结果对象,但未将其输出到控制台,导致重定向到文件时内容异常。需添加JSON格式化输出代码:
console.log(JSON.stringify(outputFileJson, null, 2));
2. 循环逻辑冗余且存在错误
for (element in filteredKeys)已经遍历filteredKeys的键,内部if (element in filteredKeys)判断完全多余;且当翻译不存在时,会给outputFileJson赋值undefined,导致JSON中出现无效的null值。优化后的循环:
for (const key of Object.keys(filteredKeys)) { const translated = translations[key]; if (translated === undefined) { notFoundTranslatedValues.push(key); // 可选:若需要保留原英文作为默认值,取消下方注释 // outputFileJson[key] = filteredKeys[key]; } else { outputFileJson[key] = translated; } }
3. 终端编码问题(Windows环境)
Windows终端默认编码非UTF-8,会导致法语特殊字符(如é、è)损坏。可改用PowerShell命令指定UTF-8编码输出:
node .\localeGenerator.js | Out-File -Encoding UTF8 outputResult
完整修复代码
/*English Strings*/ const filteredKeys = { "Select a connection" : "Select a connection", "Script Viewer" : "Script Viewer", "Execution Script" : "Execution Script", "Workflows" : "Workflows", "Select Workflow" : "Select Workflow", }; /*localized value with respect to English string*/ const translations = { "Saved Actions": "Actions enregistrées", "Select a connection": "Sélectionner une connexion", "Execution Script": "Exécution Script", "Close": "Fermer", "Workflows": "Workflows", "Select Workflow": "Sélectionner un workflow", "Clone": "Cloner" }; let outputFileJson = {}; let notFoundTranslatedValues = []; // 优化循环逻辑 for (const key of Object.keys(filteredKeys)) { const translated = translations[key]; if (translated === undefined) { notFoundTranslatedValues.push(key); // 可选:保留原英文作为 fallback // outputFileJson[key] = filteredKeys[key]; } else { outputFileJson[key] = translated; } } // 输出格式化JSON console.log(JSON.stringify(outputFileJson, null, 2)); // 可选:输出未找到翻译的字符串列表 // console.log("\n未找到翻译的字符串:", notFoundTranslatedValues);
内容的提问来源于stack exchange,提问作者Vishal
相关产品推荐
相关产品推荐

