Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda