简体   繁体   English

JSON object 数组返回未定义

[英]JSON object array return undefined

I have below scripts on Google Apps Script which will take in an JSON event.我在 Google Apps Script 上有以下脚本,它将接受 JSON 事件。 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?我猜可能是因为 events 是一个 JSON 数组,我不能直接在 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: msg 的结果将如下所示:

{
  "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.我已经在 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.我猜你从 API 得到的结果是e.postData.contentsJSON 字符串。

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 . 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.换句话说, JSON.stringify 是没用的。

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.如果“e.postData.contents”中的值已经是字符串,则不必执行 JSON.stringify。 If you do JSON.parse(JSON.stringify(any string) it results in adding backslash" to the values. For example如果您执行 JSON.parse(JSON.stringify(any string) 它会导致在值中添加反斜杠”。例如

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

myJSON = "{name: "John"}" myJSON = "{name: "John"}"

So, please make sure "e.postData.contents" is not a string.因此,请确保“e.postData.contents”不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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