有人知道如何解决我的问题吗?
编辑:感谢您的建议。我想string.replace可能是我最好的选择。但愿有一些内置功能,可以将JSON字符串中的变量转换为在JS文件中声明的变量。
在JSON文件中,您不能像在JavaScript“代码”中那样处理模板字符串文字。您自己说过。但是:您可以使用模板引擎 - 或者只是简单的String.replace()
。
模板引擎示例:https://github.com/janl/mustache.js
使用Mustache(作为示例),您的代码将如下所示:
var trans = {
command_name: "dump"
};
var output = Mustache.render("You don't have the permission to use {{command_name}}", trans);
使用简单的 String.replace()
方法:
var str = "You don't have the permission to use %command_name%";
console.log(str.replace('%command_name%', 'dump'));
const messages = {
msgName: 'Foo is :foo: and bar is :bar:!'
}
function _(key, placeholders) {
return messages[key].replace(/:(\w+):/g, function(__, item) {
return placeholders[item] || item;
});
}
使用方法:
_('msgName', { foo: 'one', bar: 'two' })
// "Foo is one and bar is two!"
这只是一个例子。您可以根据自己的需要更改占位符样式和函数行为!
./name.json
{
command: "this is the output of 'command'"
}
./Node.js
cost names = require('./name.json');
console.log('name === ', name.command);
// name === this is the output of 'command'
所以主要的挑战是如何在一些可参数化的字符串常量中获取分离的文件,对吗?
JSON格式本身操作的是字符串(数字、布尔值、列表和哈希表),并不知道替换和参数。
你也无法使用模板字符串,比如you don't have permission to do ${actionName}
,因为模板字符串会立即插值。
那么你该怎么办呢?
编写自己的解析器,从JSON文件中获取配置数据,解析字符串,找到变量的引用并将其替换为值。简单示例:
const varPattern = /\${([^{}]+)}/g; function replaceVarWithValue(templateStr, params) { return templateStr.replace(varPattern, (fullMatch, varName) => params[varName] || fullMatch); }
或者你可以使用任何旨在本地化的npm包,比如i18n,这样它就会为你处理模板。
parse
的函数,该函数接受文本和字典作为参数,它可以替换每个字典键的任何出现。
const parse = (template, textMap) => {
let output = template
for (let [id, text] of Object.entries(textMap)) {
output = output.replace(new RegExp(`\\$\{${id}}`, 'mg'), text)
}
return output
}
const textMap = {
commandName: 'grep',
foo: 'hello',
bar: 'world'
}
const parsed = parse('command "${commandName}" said "${foo} ${bar}"', textMap)
console.log(parsed)
顺便说一句,我建议你使用已有的字符串模板引擎(比如string-template),以避免重新造轮子。
commandName
作为键,并以这种方式引用它。例如,导入文件const name = require('./name.json')
并像${name.commandName}
一样使用name JSON对象。 - MrPickles