node.js 中的 json 模板引擎

use*_*550 3 javascript templates json node.js

我有一个 json 模板,如下所示:

[
  {
    "type":"foo",
    "config":"{config}"
  },
  {
    "type":"bar",
    "arrConfig":"{arrConfig}"
  }
]
Run Code Online (Sandbox Code Playgroud)

虽然我有一个支持模型,如:

{
  "config": {
    "test1": "value1",
    "test2": "value2"
  },
  "arrConfig": [
    "test3": {
      "key1": "val1"
    },
    "test4": {
      "key1": "val1"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有任何节点模块会自动采用这两个模块并转换模板中的占位符。所以输出看起来像:

[
  {
    "type":"foo",
    "config":{
      "test1": "value1",
      "test2": "value2"
    }
  },
  {
    "type":"bar",
    "arrConfig": [
      "test3": {
        "key1": "val1"
      },
      "test4": {
        "key1": "val1"
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

Tia*_*gel 6

JSON.stringify 接受一个你可以用来做它的替换参数。

这应该有效:

var template = [
  {
    "type":"foo",
    "config":"{config}"
  },
  {
    "type":"bar",
    "arrConfig":"{arrConfig}"
  }
];


var data = {
  "config": {
    "test1": "value1",
    "test2": "value2"
  },
  "arrConfig": {
    "test3": {
      "key1": "val1"
    },
    "test4": {
      "key1": "val1"
    }
  }
};

var replacer = function (key, val) {
   if (typeof val === 'string' && val.match(/^{(.+)}$/)) {
     return data[val.replace(/[{|}]/g, '')]
   }
   return val;
 }

 console.log(JSON.stringify(template, replacer));
Run Code Online (Sandbox Code Playgroud)

如果你想把它转换回一个对象,你可以使用 JSON.parse