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

149
Visualizações
JSON object array return undefined

I have below scripts on Google Apps Script which will take in an JSON event. I want the data in element "events", but it always return "Undefined" to me.

I'm guessing maybe it's because events is a JSON array and I can't directly use it in JS?

Here is my code:

function doPost(e) {
  var msg = JSON.parse(JSON.stringify(e.postData.contents));
  
  console.log(msg);
  //log succesfully

  console.log(msg.events);
  //"Undefined"
}

If I try to log the elements in the events instead of the array events itself:

  console.log(msg.events[0].replyToken);
  //"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"

The result of msg will is in below:

{
  "destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
  "events": [
    {
      "type": "message",
      "message": {
        "type": "text",
        "id": "*********",
        "text": "Hi"
      },
      "timestamp": 1642616050062,
      "source": {
        "type": "group",
        "groupId": "***********",
        "userId": "*************"
      },
      "replyToken": "************",
      "mode": "active"
    }
  ]
}

I've seen several similar problems for array in JS. I tried them but all of them didn't work, please help me.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I guess the result your getting from your API as e.postData.contents is a JSON string.

In this case something like this:

var msg = JSON.parse(JSON.stringify(e.postData.contents));

would first try to turn something into a JSON string (JSON.stringify) and then converting it into a JavaScript object by JSON.parse. In other words the JSON.stringify is useless.

Try this instead:

var msg = JSON.parse(e.postData.contents);
about 4 years ago · Juan Pablo Isaza Relatório

0

If the value from "e.postData.contents" is already a string, you don't have to do JSON.stringify. If you do JSON.parse(JSON.stringify(any string) it results in adding backslash" to the values. For example

let str = '{name: "John"}';
let myJSON = JSON.stringify(str);
 

myJSON = "{name: "John"}"

So, please make sure "e.postData.contents" is not a string.

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