JSON 插值:需要将变量从 .js 文件注入到 .json 文件中以实现 REST (POST)

JSON Interpolation: Need to inject variables into a .json file from a .js file for a REST (POST)

我想做什么:

1) Post 到我的 API 和我的 .json 文件(包含我需要的整个正文

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


 // 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);
  });
});

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

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

您要做什么:更改 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 对象,您可以将其传递给请求的正文

首先,您必须在 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 文件将您的 post 请求发送到您的服务器。

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

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

我可能会在这个流程中迟到,请多多包涵。 我自己遇到了同样的问题并写了一个小 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>' }