【发布时间】:2018-06-24 10:37:44
【问题描述】:
如何解析这样的 JSON?这是要提取到 Google 电子表格中的 Keenio 提取 API 查询数据。
我尝试使用以下代码解析返回的 JSON,但不知道如何访问嵌套对象和数组。
function myFunction() {
var URL = "https://api.keen.io/3.0/projects/" +
PROJECT_KEY + "/queries/extraction?api_key=" +
API_KEY + "&event_collection=" +
EVT_COL + "&timezone=" +
TIMEZONE + "&latest=" +
LATEST + "&property_names.........."
var response = UrlFetchApp.fetch(URL);
var json = response.getContentText();
var rawdata = JSON.parse(response.getContentText());
Logger.log(rawdata.result);
var data = [];
data.push(rawdata.result);
SpreadsheetApp.getActiveSheet().appendRow(data);
}
上面我写了一个简单的函数来解析这个 JSON,但是我无法使用点符号来获取嵌套的对象和数组。
我在使用著名的 IMPORTJSON 代码时观察到的另一件事是,每次出现的列顺序都是打乱的,所以我在返回的数据上编写的公式会导致引用错误。
{
"result": [
{
"sg_event_id": "92-OndRfTs6fZjNdHWzLBw",
"timestamp": 1529618395,
"url": "https://noname.com?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email",
"ip": "192.168.1.1",
"event": "click",
"keen": {
"timestamp": "2018-06-21T21:59:55.000Z",
"created_at": "2018-06-21T22:00:28.532Z",
"id": "555c1f7c5asdf7000167d87b"
},
"url_offset": {
"index": 38,
"type": "text"
},
"sg_message_id": "F5mwV1rESdyKFA_2bn1IEQ.filter0042p3las1-15933-5B2A68E8-36.0",
"useragent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)",
"email": "no.name@noname.com"
}, {
"sg_event_id": "bjMlfsSfRyuXEVy8LndsYA",
"timestamp": 1529618349,
"url": "https://noname.com?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email",
"ip": "192.168.1.1",
"event": "click",
"keen": {
"timestamp": "2018-06-21T21:59:09.000Z",
"created_at": "2018-06-21T21:59:39.491Z",
"id": "555c1f7c5asdf7000167d87b"
},
"url_offset": {
"index": 36,
"type": "text"
},
"sg_message_id": "F5mwV1rESdyKFA_2bn1IEQ.filter0042p3las1-15933-5B2A68E8-36.0",
"useragent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)",
"email": "no.name@noname.com"
}, {
"sg_event_id": "fru_s2s1RtueuqBMNoIoTg",
"timestamp": 1529618255,
"url": "https://noname.com?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email",
"ip": "192.168.1.1",
"event": "click",
"keen": {
"timestamp": "2018-06-21T21:57:35.000Z",
"created_at": "2018-06-21T21:58:20.374Z",
"id": "555c1f7c5asdf7000167d87b"
},
"url_offset": {
"index": 29,
"type": "text"
},
"sg_message_id": "F5mwV1rESdyKFA_2bn1IEQ.filter0042p3las1-15933-5B2A68E8-36.0",
"useragent": "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)",
"email": "no.name@noname.com"
}
]
}
【问题讨论】:
-
请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
-
@halfer 谢谢。知道了! :)
标签: json google-apps-script google-sheets sendgrid keen-io