首页 > 解决方案 > 无法访问对象内的数据 - 菜鸟 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
  }
}

标签: javascriptnode.jsarraysjsonget

解决方案


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);
    });
  }
);

推荐阅读