0

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.

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

OMG! Thank you! It worked! I had a "Unexpected token o in JSON at position 1 at doPost" error, so I add stringify. I didn't expect it will cause problem....
No problem - glad I could help! =) By the way, if you think this is the correct answer please consider accepting it using the tick button.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.