[英]How do I loop JSON response to get specific data in Javascript or GAS
I Have an JSON response from an external API.我有来自外部 API 的 JSON 响应。 Problem is i only know how to log the response but not manipulate it.
问题是我只知道如何记录响应但不知道如何操作它。 In this case, I need to get some information from the response and loop through the entire response to show the list of all the users.
在这种情况下,我需要从响应中获取一些信息并遍历整个响应以显示所有用户的列表。 Here is my code so far.
到目前为止,这是我的代码。 Its not a good one, but this what i could do with my minimal javascript skills.
它不是一个好方法,但这是我可以用我最少的 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)
}
Sample response:示例响应:
"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,
},
You can use Array.prototype.map
to iterate through data and return required information only from the object您可以使用
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)
If ES6 is not supported如果不支持 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.