[英]JSON object array return undefined
我在 Google Apps Script 上有以下腳本,它將接受 JSON 事件。 我想要元素“事件”中的數據,但它總是向我返回“未定義”。
我猜可能是因為 events 是一個 JSON 數組,我不能直接在 JS 中使用它?
這是我的代碼:
function doPost(e) {
var msg = JSON.parse(JSON.stringify(e.postData.contents));
console.log(msg);
//log succesfully
console.log(msg.events);
//"Undefined"
}
如果我嘗試記錄事件中的元素而不是數組事件本身:
console.log(msg.events[0].replyToken);
//"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"
msg 的結果將如下所示:
{
"destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
"events": [
{
"type": "message",
"message": {
"type": "text",
"id": "*********",
"text": "Hi"
},
"timestamp": 1642616050062,
"source": {
"type": "group",
"groupId": "***********",
"userId": "*************"
},
"replyToken": "************",
"mode": "active"
}
]
}
我已經在 JS 中看到了幾個類似的數組問題。 我嘗試了它們,但它們都不起作用,請幫助我。
我猜你從 API 得到的結果是e.postData.contents
是JSON 字符串。
在這種情況下是這樣的:
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
. 換句話說, JSON.stringify 是沒用的。
試試這個:
var msg = JSON.parse(e.postData.contents);
如果“e.postData.contents”中的值已經是字符串,則不必執行 JSON.stringify。 如果您執行 JSON.parse(JSON.stringify(any string) 它會導致在值中添加反斜杠”。例如
let str = '{name: "John"}';
let myJSON = JSON.stringify(str);
myJSON = "{name: "John"}"
因此,請確保“e.postData.contents”不是字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.