Home > OS >  Changing braces in a string with data from a json
Changing braces in a string with data from a json

Time:07-01

I have a template string that I want to change words with {{}} around them to data of a similar name from a json file. I am using google apps script for this.

Ex. Hello my name is {{First Name}} {{Last Name}}. --> Hello my name is Sherlock Holmes.

Json file would be:

[ { 'First Name': 'Sherlock',
'Last Name': 'Holmes'  }  ]

I have tried using this code where template is the string and data is the json:

function fillInTemplateFromObject(template, data) {
   let template_string = template;

   // Token replacement
   template_string = template_string.replace(/{{[^{}] }}/g, key => {
     return escapeData_(data[key.replace(/[{}] /g, "")] || "");
   });
   return  JSON.parse(template_string);
  }

  function escapeData_(str) {
    return str
      .replace(/[\\]/g, '\\\\')
      .replace(/[\"]/g, '\\\"')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t');
  };

But it just removes the braces instead of replacing them. ex. Hello my name is .

Any help would be appreciated.

CodePudding user response:

Since your data variable is a dictionary within an array, referencing data[key.replace(/[{}] /g, "")] returns undefined. This can be remedied by instead inputting the following for your data variable.

{ 'First Name': 'Sherlock',
'Last Name': 'Holmes' }

Additionally, parsing template_string is unnecessary.

function fillInTemplateFromObject(template, data) {
   let template_string = template;

   // Token replacement
   template_string = template_string.replace(/{{[^{}] }}/g, key => {
     return escapeData_(data[key.replace(/[{}] /g, "")] || "");
   });
   return template_string;
  }

  function escapeData_(str) {
    return str
      .replace(/[\\]/g, '\\\\')
      .replace(/[\"]/g, '\\\"')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t');
  };
  • Related