【问题标题】:Unable to get the length of JSON object无法获取 JSON 对象的长度
【发布时间】:2018-08-27 22:29:10
【问题描述】:

我在尝试访问 nodejs 中 json 对象的长度时收到“TypeError: Cannot convert undefined or null to object”。

以下是我的数据的样子:

{
  "college": [
    {
      "colleges": [],
      "department": [
        1,
        2,
        3
      ],
      "general_course": [],
      "id": 1,
      "name": "College of the Arts",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1919"
    },
    {
      "colleges": [],
      "department": [
        4,
        5,
        6
      ],
      "general_course": [],
      "id": 2,
      "name": "College of Communications",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1920"
    },
    {
      "colleges": [],
      "department": [
        7,
        12
      ],
      "general_course": [],
      "id": 3,
      "name": "College of Education",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1921"
    },
    {
      "colleges": [],
      "department": [
        13,
        17,
        19
      ],
      "general_course": [],
      "id": 4,
      "name": "College of Engineering and Computer Science",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1922"
    },
    {
      "colleges": [],
      "department": [
        20,
        26,
        27
      ],
      "general_course": [],
      "id": 5,
      "name": "College of Health and Human Development",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1923"
    },
    {
      "colleges": [],
      "department": [
        28,
        29,
        32,
        48
      ],
      "general_course": [],
      "id": 6,
      "name": "College of Humanities and Social Sciences",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1924"
    },
    {
      "colleges": [],
      "department": [
        52,
        57
      ],
      "general_course": [],
      "id": 7,
      "name": "College of Natural Sciences and Mathematics",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1925"
    },
    {
      "colleges": [],
      "department": [
        58,
        59,
        63
      ],
      "general_course": [],
      "id": 8,
      "name": "Mihaylo College of Business and Economics",
      "short_name": "",
      "url": "/content.php?catoid=16&navoid=1926"
    }
  ]
}

第 1 步 - 将其解析为 nodejs:

let colleges = JSON.parse(data)

第 2 步 - 将其保存到对话流应用数据中:

app.data.collegeData = data;

第 3 步 - 获取长度:

let collegeLength = Object.keys(app.data.collegeData.college).length;

在 Firebase 控制台中出现以下错误:

TypeError: 无法将 undefined 或 null 转换为对象

更新:

代码如下:

if ( app.data.collegeData === undefined ){
    app.data.collegeData = [];
}

**Step 1 =>** 

showColleges(college);

**Step 2 =>**

  function showColleges(collegeName){
      if (app.data.collegeData.length === 0){
          getCollegeData().then(buildSingleCollegeResponse(collegeName))
              .catch(function (err){
                  console.log('No college data')
                  console.log(err)
              });
      }
      else{
          buildSingleCollegeResponse(collegeName);
      }
  }

**Step 3 =>**

 function getCollegeData(){
      console.log('Inside get College Data')
      return requestAPI(URL)
          .then(function (data) {
              let colleges = JSON.parse(data)
              if (colleges.hasOwnProperty('college')){
                  saveData(colleges)
              }
              return null;
          })
          .catch(function (err) {
              console.log('No college data')
              console.log(err)
          });
  }

**Step 4 =>**

  function saveData(data){
      app.data.collegeData = data;
      console.log(app.data.collegeData)
  }

**Step 5 =>**

function buildSingleCollegeResponse(collegeName){
      let responseToUser, text;
      //console.log('Data is -> '+ Object.keys(app.data.collegeData.college).length);
      //console.log('Length is -> '+ app.data.collegeData.college.length);
      console.log('Count is -> '+app.data.collegeCount);

      let collegeLength = Object.keys(app.data.collegeData.college).length;

      if ( collegeLength === 0){
          responseToUser = 'No colleges available at this time';
          text = 'No colleges available at this time';
      }
      else if ( app.data.collegeCount < collegeLength ){

          for ( var i = 1; i <= collegeLength; i++)
          {
              console.log('All Colleges:: '+app.data.collegeData.college[i])
              let coll = app.data.collegeData.college[i]
              let name = coll.name
              console.log('checkCollegeExist => College Name:: '+ name)
              console.log('checkCollegeExist => Parameter => College Name:: '+collegeName)

              if(String(name).valueOf() === String(collegeName).valueOf()){
                  responseToUser = 'Yes! CSUF has '+collegeName;
                  text = 'Yes! CSUF has '+collegeName;
              }else{
                  responseToUser = 'CSUF does not teach ' +collegeName+' currently';
                  text = 'CSUF does not teach ' +collegeName+' currently';
              }
          }
      }
      else{
          responseToUser = 'No more colleges';
      }
      if (requestSource === googleAssistantRequest) {
          sendGoogleResponse(responseToUser);
      } else {
          sendResponse(text);
      }
  }

【问题讨论】:

  • 第一步:let colleges = JSON.parse(data) 然后第二步:app.data.collegeData = data; 不应该是= colleges吗? data 仍然是一个字符串 (JSON),但您希望使用 colleges 中的实际数据(这不是 JSON,因为它不是字符串)。
  • 投票以拼写错误/非复制/未来无用的方式关闭,因为如果您解决上述简单错误,它会起作用:jsfiddle.net/dktaknrc
  • 谢谢!更新了我的问题。如果有帮助,请发布更多代码。
  • Javascript 中只有一个 JSON 对象,它用于(反)序列化 JSON 格式的字符串。你要么有一个 JSON 格式的字符串,要么有一个 JavaScript 对象。
  • @ch4nd4n 不完全是我得到的,“json object”的 OPs 用法不正确。 benalman.com/news/2010/03/theres-no-such-thing-as-a-json

标签: json node.js firebase firebase-realtime-database dialogflow-es


【解决方案1】:

这是罪魁祸首:

getCollegeData().then(buildSingleCollegeResponse(collegeName))

调用buildSingleCollegeResponse(collegeName),然后将其返回值传递给then,就像foo(bar()) 调用 bar和将其返回值传递给foo

您想将函数传递给then

getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

请注意,现在从更新的问题中可以清楚地看出app.data.collegeData.college 是一个数组,因此不需要Object.keys。变化:

let collegeLength = Object.keys(app.data.collegeData.college).length;

简单

let collegeLength = app.data.collegeData.college.length;

数组有一个length 属性(而非数组对象默认没有)。

【讨论】:

  • 哦.. 非常感谢。
【解决方案2】:

在发出 app.data.collegeData = data; 之前,您还没有提到 app.data 的价值

如果app.data 未定义,您应该尝试app.data = {collegeData: data}

否则否定应用商店。以下作品

app = {};
app.data = {};
app.data.collegeData = data;

app.data.collegeData.college.length

您不需要执行以下操作

let collegeLength = Object.keys(app.data.collegeData.college).length;

更新:参考https://jsfiddle.net/dmxuum79/3/

【讨论】:

  • @PuneetJain 如果app.data 是有效对象,您没有回答。如果除非 app.data 有效,否则不能分配 app.data.collegeData。
  • 谁投了反对票,请解释一下为什么它被否决了?
  • 是的,它有效。
  • getCollegeData().then(buildSingleCollegeResponse(collegeName)) 这就是问题所在。不过谢谢!
猜你喜欢
  • 2014-04-30
  • 2015-03-24
  • 1970-01-01
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多