【问题标题】:Inject JavaScript variables into JSON file (Node.js)将 JavaScript 变量注入 JSON 文件 (Node.js)
【发布时间】:2026-02-10 05:05:01
【问题描述】:

我正在尝试创建一个站点,您只需制作文件即可在其中轻松添加页面。为了注入,我通过 JSON 文件 (keys.json) 传入数据。我将如何做到这一点,以便能够将变量注入文件中。这是我制作的一个示例。

JS:

app.get('*', async (req, res) => {
    var URL = '/i/d/k';
    keys = JSON.parse(v[3]); //v[3] is the JSON file as a string (where it comes from is irrelevant)
    //insert vars into keys here
    html = await U.inject(html, keys);
    res.send(html);
});

keys.json:

{
  "title": "Hi"
  "url": URL
  "user": req.body.user
}

html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <title>{{title}}</title>
  </head>
  <body>
    <p>{{user}}, you have visited: {{url}}</p>
</html>

我该怎么做呢?甚至可能吗?感谢您的帮助!

注意:在 keys.json 中插入字符串按预期工作,并且该项目被替换。

【问题讨论】:

  • 我会使用任何模板机制。
  • @DaveNewton 你有什么好的建议吗?
  • 随便挑一个...

标签: javascript node.js json express


【解决方案1】:

解析完 JSON 后,您可以像访问任何其他对象一样访问和更改其值。

const myJSON = '{"one":1,"two":2,"three":3,"four":5}';

const myObject = JSON.parse(myJSON);

console.log(myObject);

myObject.four = 4;

console.log(myObject);

const myConst = 5;

myObject.five = myConst;

console.log(myObject);

所以使用您的示例代码,您可以这样做:

app.get('*', async (req, res) => {
    var URL = '/i/d/k';
    keys = JSON.parse(v[3]); //v[3] is the JSON file as a string (where it comes from is irrelevant)

    keys.url = URL;
    keys.user = req.body.user;
    
    html = await U.inject(html, keys);
    res.send(html);
});

如果您需要在某处保存值,请使用数据库或密钥存储。

【讨论】:

  • 是的,但我想只用 JSON 来做这件事,而不是在我添加另一个页面时更改任何 JavaScript。