我在 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"
}
]
}
我已經在 J??S 中看到了幾個類似的陣列問題。我嘗試了它們,但它們都不起作用,請幫助我。
uj5u.com熱心網友回復:
我猜你從 API 中得到的結果e.postData.contents 是JSON 字串。
在這種情況下是這樣的:
var msg = JSON.parse(JSON.stringify(e.postData.contents));
將首先嘗試將某些內容轉換為 JSON 字串 ( JSON.stringify),然后將其轉換為 JavaScript 物件JSON.parse。換句話說 JSON.stringify 是沒用的。
試試這個:
var msg = JSON.parse(e.postData.contents);
uj5u.com熱心網友回復:
如果“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”不是字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/416495.html
標籤:
