【问题标题】:JSON Interpolation: Need to inject variables into a .json file from a .js file for a REST (POST)JSON 插值:需要将变量从 .js 文件注入 .json 文件以进行 REST (POST)
【发布时间】:2018-08-29 20:56:02
【问题描述】:

我想做的事:

1) 使用我的 .json 文件发布到我的 API(包含我需要的整个正文

2) 在 .json 文件中,我想使用像 ${value} 这样的变量,然后从我的 .js 文件中获取该值并替换 .json 文件中的 var

  • 目前使用带 Mocha 的 NodeJS。我有我的 API 调用(下面的 .js 代码):

 // for brevity - I removed the other dependencies
 const jsonconfig_post = require('./POST.json'); // this is my .json file

describe('\nPOST <TO MY ENDPOINT> \n', function() {
    const apiBase = `<MY ENDPOINT>`;
    const cookieJar = request.jar();
    var nameDate = new time.Date();

beforeEach(function(done) {
    this.timeout(5000);
    common.verifyLogin(cookieJar, done); //calls my login code
});

it('POST 1: <MY ENDPOINT> - POST', function(done) {
    const title = 'NodeJS_Project';
    let requestBody = jsonconfig_post(title + nameDate);
    //NodeJS_Project is the Var name and nameDate is the appended date
    this.timeout(5000);
    const opts = {
        jar: cookieJar,
        uri: `${apiBase}/<MY ENDPOINT>`,
        method: 'POST',
        json: true,
        headers: {
            "Content-Type": "application / json",
            "Accept": "text / json"
        },
        body: (requestBody), // POST to my API with this
    };
    request(opts).then(() => {
        opts.body = {};
        console.log(requestBody);
        done();
    }).catch(done);
  });
});
  • 我的 POST.json 文件 - 如下。我想使用 ${title} 并将其替换为我的 .js 代码中的内容 - “NodeJS_Project”。

 {
 "title": "${title}",
 "Id": "<SOME ID>"
 }

学习 NodeJS/Mocha 并且到目前为止非常喜欢它。我可以在使用 .json 文件之外完成这项工作 - 但是使用 .json 文件使事情变得更容易就 .js 的外观而言,例如简单干净。这是一个小例子 - 其他 POST 调用使用了一个巨大的 json 主体(许多嵌套元素),因此在这种情况下使用 .json 非常有价值,例如替换 .json 文件中的许多变量/值。我知道这可以工作,我希望?我目前得到 400 并且可以看到 JSON 没有正确传递到端点 - 或者 - 我只是发布了变量 ${title} (不是我想要的)。任何帮助都会非常感激。 注意 - 我已经尝试了许多其他使用 JSON.parse/stringify 等的方法,但都失败了 - 或者 - 我没有正确使用(肯定可能是这种情况:))。 提前致谢 干杯! -E

【问题讨论】:

    标签: json node.js mocha.js interpolation string-interpolation


    【解决方案1】:

    您要做什么:更改 json 文件? 这是可能的,但我认为这不是您想要实现的目标。

    您想要实现的是干净的代码,因此您将 requestBody 提取到外部文件中,对吧?

    所以我认为要走的路是创建一个 javascript 文件 (post.js),在其中创建一个对象 jsonconfig_post 并导出

    exports.jsonconfig_post = {
      title: '${title}',
      Id: '<SOME ID>',
    };
    

    所以现在你可以在你的代码中导入这个对象

    const { jsonconfig_post } = require('./POST.js');
    

    这是一个你可以像这样修改的对象

    const jsonconfigWithValues = Object.assign({}, jsonconfig_post, { title: 'NodeJS_Project' });
    

    现在你有了一个 json 对象,你可以通过你的请求正文传递它

    【讨论】:

    • 非常感谢@horstenwillem 的回复!我正在尝试你的建议。如果我无法正常工作,我会回复我的发现和/或问题。
    • 上述解决方案效果很好!感谢您和@Terrtiary 的快速回复。此帖已回复!极好的! -干杯! -E
    【解决方案2】:

    首先,您必须在 Javascript 代码中读取 JSON 文件。最好的方法是使用内置的fs 模块。

    1. 先导入FS:

      const fs = require('fs');
      

      然后将 JSON 从您的文件加载到一个变量中,并将该 JSON 存储为 Javascript 对象。重要的是不要被 Javascript 对象和 JSON 不是一回事这一事实所混淆。你可以看看here.

    2. 要使用 fs 导入 JSON 文件,请执行以下操作:

      var importedData = JSON.parse(fs.readFileSync('POST.json', 'utf8'));
      

      您也可以异步读取文件,但我假设您现在想要同步执行所有操作。

    3. 现在您要替换占位符数据,就像替换普通对象一样。尽管从技术上讲,您可以遍历对象并使用 ${TITLE} 搜索字符串,但您并没有真正像模板那样替换值,但我们将在这里以直接的方式进行操作。像这样的:

      importedData.title = 'TITLE';
      
    4. 现在将该对象写回您的原始文件:

      fs.writeFileSync('POST.json', importedData, 'utf8' function(err) {
        if(err) {
          console.log(err);
        }
      });
      
    5. 现在您可以使用新的 JSON 文件将您的发布请求发送到您的服务器。

      it('POST 1: <MY ENDPOINT> - POST', function(done) {
          ...
      });
      

    我主要使用一般示例,但这基本上就是您要寻找的。如果您对实施有任何疑问,请告诉我。

    【讨论】:

    • 非常感谢@Terrtiary 的回复!我正在尝试你的建议。如果我无法正常工作,我会回复我的发现和/或问题。
    【解决方案3】:

    我可能迟到了,请多多包涵。 我自己也遇到了同样的问题,写了一个小 npm 插件interpolate-json

    // declare library variable
    const interpolation = require('interpolate-json').interpolation;
    // or
    const { interpolation } = require('interpolate-json');
    
    // The json with a variable placeholder
    var postJson = {
      title: '${title}',
      Id: '<SOME ID>',
    };
    
    // replace placeholders with values, passed as json
    var postJsonWithValue = interpolation.expand(postJson, {
      title: 'My Favourite Title',
    });
    
    // If you have different placeholder variable baoundary, like `{{ title }}`
    // you can set that as a option object in 3rd parameter
    // (more details in plugin documentation)
    var postJsonWithValue = interpolation.expand(
      postJson,
      {
        title: 'My Favourite Title',
      },
      { prefix: '{{', suffix: '}}' }
    );
    
    console.log(postJsonWithValue);
    // output: { title: 'My Favourite Title', Id: '<SOME ID>' }
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2016-08-11
      • 2013-10-26
      相关资源
      最近更新 更多