[英]How do I access children data in JSON response using Javascript/GAS
[英]How do I loop JSON response to get specific data in Javascript or GAS
我有來自外部 API 的 JSON 響應。 問題是我只知道如何記錄響應但不知道如何操作它。 在這種情況下,我需要從響應中獲取一些信息並遍歷整個響應以顯示所有用戶的列表。 到目前為止,這是我的代碼。 它不是一個好方法,但這是我可以用我最少的 javascript 技能做的事情。
};
var response= UrlFetchApp.fetch(url, options)
var call= JSON.parse(response.getContentText());
var people=call.data;
var user= {}
user.ID = call.data[1].id;
user.Email = call.data[1].email;
user.Name= call.data[1].display_name;
Logger.log(user)
}
示例響應:
"data": [
{
"id":00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test@test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
},
"data": [
{
"id":00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test@test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
},
您可以使用Array.prototype.map
遍歷數據並僅從對象返回所需的信息
let data = [ { "id": 00126, "first_name": "Test", "last_name": "Test", "archived": false, "display_name": "Test Test", "email": "test@test.com", "termination_date": null, "mobile_phone": null, "office_phone": null, "deleted_at": null, "deleted": false, }] let res = data.map(({id, email, display_name}) => ({ID: id, Email: email, Name: display_name})); console.log(res)
如果不支持 ES6
var res = data.map(function(userData) {
return {ID: userData.id, Email: userData.email, Name: userData.display_name}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.