NodeJS在JSON文件字符串中使用变量

3
我使用JSON文件存储常用短语,这样就不必手动输入它们,并且也许将来可以进行翻译。所以例如,在我的主要代码中,我想说"你没有权限使用${command_name}"。在我的.js文件中硬编码可以正常工作,但是最终我希望它在JSON文件中,而JSON文件不允许插入任何变量。
有人知道如何解决我的问题吗?
编辑:感谢您的建议。我想string.replace可能是我最好的选择。但愿有一些内置功能,可以将JSON字符串中的变量转换为在JS文件中声明的变量。

你需要在JSON文件中将commandName作为键,并以这种方式引用它。例如,导入文件const name = require('./name.json')并像${name.commandName}一样使用name JSON对象。 - MrPickles
6个回答

3

在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'));

1
您可以使用占位符。以下函数将占位符替换为用户定义的值:
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!"

这只是一个例子。您可以根据自己的需要更改占位符样式和函数行为!


0

./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'

0

您可以使用config npm模块,根据您的环境将JSON文件分开。


0

所以主要的挑战是如何在一些可参数化的字符串常量中获取分离的文件,对吗?

JSON格式本身操作的是字符串(数字、布尔值、列表和哈希表),并不知道替换和参数。

你也无法使用模板字符串,比如you don't have permission to do ${actionName},因为模板字符串会立即插值。

那么你该怎么办呢?

  1. 编写自己的解析器,从JSON文件中获取配置数据,解析字符串,找到变量的引用并将其替换为值。简单示例:

    const varPattern = /\${([^{}]+)}/g; function replaceVarWithValue(templateStr, params) { return templateStr.replace(varPattern, (fullMatch, varName) => params[varName] || fullMatch); }

  2. 或者你可以使用任何旨在本地化的npm包,比如i18n,这样它就会为你处理模板。


0
基本上,您可以实现一个名为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),以避免重新造轮子。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接