Search code examples
jsonnode.jsmocha.jsinterpolationstring-interpolation

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


What I'm trying to do:

1) Post to my API with my .json file (that contains the entire body that I need)

2) From within the .json file I want to use a variable like ${value} to then take that value from my .js file and replace the var in the .json file

  • Currently using NodeJS w/Mocha. I have my API call (.js code below):

 // 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);
  });
});
  • My POST.json file - below. I want to take ${title} & replace that with what I have in my .js code - "NodeJS_Project".

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

learning NodeJS/Mocha & really liking it so far. I can make this work outside of using the .json file - but the use of the .json file makes things SO much easier in terms of what the .js looks like e.g. simple and clean. This is a small example - the other POST calls have use a HUGE json body (many nested elements), so the use of the .json, in this case, is very valuable e.g replacing many variables/values in a .json file. I know this can work, I hope? I'm getting a 400 currently and can see that the JSON is not getting passed to the endpoint correctly -OR- I just get the variable ${title} posted (not what I want). Any help would be So immensely appreciated. note - I've tried a number of other approaches using JSON.parse/stringify etc. but that has failed -OR- I'm not using correctly (surely could be the case :)). Thanks in advance Cheers! -E


Solution

  • What you are trying to: altering a json file? This is possible but I don't think that it is what you are trying to achieve.

    What you want to achieve is clean code so you extracted your requestBody into an external file, right?

    So what I think the way to go is here, is to create a javascript file (post.js) in which you create an object jsonconfig_post that you export

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

    So now you can import this object in your code like

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

    And this is an object that you can modify like this

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

    And now you have a json object that you can pass through the body of your request