javascript - 无法访问对象内的数据 - 菜鸟 Javascript 问题
问题描述
这是一个关于访问对象内的数组并将其转换为 JSON 的菜鸟问题。
运行以下 GET 方法时出现错误:
无法读取未定义的属性“VehicleList”
如何解决这个问题?
let get = https.get(
{
hostname: 'xyz.com',
path: path_get_all_vehicles //this variable is known and passed into path
},
(getRes) => {
console.log(`executing getRes...`);
var reply = "";
getRes.on("data", (chunk) => {
(reply += chunk);
}
);
getRes.on("end", () => {
gotCars(JSON.parse.stringify(reply.Response.VehicleList)); //ERROR
}
);
}
);
数据格式如下图所示,思路是访问 VehicleList 数组,将其转换为 JSON,然后将其解析后传递给函数gotCars
{
"ResponseStatus": 1,
"Response": {
"VehicleList": [
{
"ID": AAA,
"BrandID": 89,
"ModelID": 980,
"VersionID": 11289
},
{
"ID": BBB,
"BrandID": 89,
"ModelID": 980,
"VersionID": 8338
},
],
"VehicleCount": 17866
}
}
解决方案
JSON.parse.stringify(reply.Response.VehicleList)
由于以下几个原因,该表达式无效:
- 全局
JSON.parse
没有名为stringify
(undefined
)的属性 undefined
无法调用- 全局
String.prototype
(reply
是字符串) 没有名为Response
(undefined
)的属性 undefined
不能被索引
我假设您正在尝试解析reply
为 JSON,然后VehicleList
从结果中获取数组,请尝试以下代码:
let get = https.get(
{
hostname: "xyz.com",
path: path_get_all_vehicles // this variable is known and passed into path
},
(getRes) => {
console.log(`executing getRes...`);
var reply = "";
getRes.on("data", (chunk) => {
reply += chunk;
});
getRes.on("end", () => {
gotCars(JSON.parse(reply).Response.VehicleList);
});
}
);
推荐阅读
- azure-devops - 有没有办法将 gitignore 模板添加到 azure devops 中的新项目?
- excel - 搜索以连接列并在从另一个工作簿中选择额外数量之间,该数量应增加
- javascript - react-native-webrtc 远程流在 android 5.0.2 上不起作用
- sql - 如何提取SAS PROC SQL passthru中的记录,按日期过滤,但日期是字符串格式?
- javascript - 如何为每个 wordpress 帖子点击创建单独的弹出表单
- reactjs - 设置标题React的行数
- linux - 如何通过 ssh 将 VSC 与 Fedora 连接?
- docker - 更新 docker 上的根证书
- typescript - 汇总:从外部模块捆绑/嵌入 wasm 代码
- javascript - 由于大量 JSON 响应,AJAX 请求失败