无法访问对象内的数据 - 菜鸟 Javascript 问题
Can't access data inside an object - rookie Javascript question
这是一个关于访问对象内部数组并将其转换为 JSON 的菜鸟问题。
当 运行 使用下面的 GET 方法时出现错误:
Cannot read property 'VehicleList' of undefined
如何解决这个问题?
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
}
}
您首先需要解析 reply
,这将创建对象。然后就可以访问它的属性了。
getRes.on("end", () => {
const obj = JSON.parse(reply);
gotCars(obj.Response.VehicleList);
});
表达式 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);
});
}
);
这是一个关于访问对象内部数组并将其转换为 JSON 的菜鸟问题。
当 运行 使用下面的 GET 方法时出现错误:
Cannot read property 'VehicleList' of undefined
如何解决这个问题?
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
}
}
您首先需要解析 reply
,这将创建对象。然后就可以访问它的属性了。
getRes.on("end", () => {
const obj = JSON.parse(reply);
gotCars(obj.Response.VehicleList);
});
表达式 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);
});
}
);