Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
Changing braces in a string with data from a json

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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');
  };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!