简体   繁体   中英

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM