您好,我正在尝试访问来自JSON的特定密钥。我使用的是node.js和angular 7,我得到的JSON是stringfy,它来自一个应用程序接口。
这是我得到的JSON
"search": {
"entry": [
{
"dn": "uid=080030781,c=mx,ou=s,o=i.com",
"attribute": [
{ "name": "mail", "value": ["CAMILA.CAMPOS.TELLEZ@mail.com", "MX08@mail.com"] }]
}
],
"return": {
"code": 0,
"message": "Success",
"count": 1
}
}
}我需要访问键" value ",因为我需要获取值"camila.campos.tellez@mail.com“。我从一个名为app.js的node.js文件中声明的应用程序接口中获取JSON,然后使用这个service.ts文件捕获来自它的响应
getApproverMail(name) {
console.log('entered to rootservice');
return this.http.get(this.baseUrl + '/costing/operations?name=' + name);
}最后,我可以使用下面的代码通过component.ts文件访问它
findApproverMail() {
this.rootService.getApproverMail(this.aproverName).subscribe((res) => {
this.email = res;
console.log('Test: ' + res);
});
}浏览器控制台将打印我向您展示的JSON。但是,我如何才能只访问邮件的价值呢?附注:我只需要邮件,因为在我得到它后,网站需要发送电子邮件到那个方向
发布于 2019-09-27 03:57:59
JSON代表JavaScript Object Notation。任何有效的JSON都是JavaScript (和TypeScript)中的对象。您可以使用点符号导航到对象中:
findApproverMail() {
this.rootService.getApproverMail(this.aproverName).subscribe((res) => {
this.email = res.search.entry[0].attribute[0].value[0];
console.log('Test: ' + res);
});
}我建议以您期望从服务中获得的形式来定义一个interface。它比仅仅围绕any类型的对象进行索引要干净得多。
还要注意,我对0索引进行了硬编码,因为它回答了您的问题。您可以考虑一种更动态/更灵活的方式来获取所需的地址或元素。
https://stackoverflow.com/questions/58123836
复制相似问题