You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中获取JSON对象长度报错:无法获取长度及TypeError求助

Fixing JSON Length Issues & TypeError in Node.js

Alright, let's break down your two issues step by step, using the sample data you provided. First, let's recap your data structure to make sure we're on the same page:

{ "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": "/con..." } ] }


1. "Unable to get the length of JSON object"

The core issue here is mixing up arrays and plain objects in JavaScript:

  • Arrays have a built-in length property, but plain objects (like each individual college entry in your array) do not.
  • In your data, college is an array containing 2 college objects. So if you're trying to get the number of colleges, you need to target the array, not the objects inside it.

Solutions based on what you need:

Get the number of colleges (length of the college array):

// First, make sure you've parsed your JSON string into a JS object
const parsedData = JSON.parse(yourJsonString);

// Access the array's length property
const collegeCount = parsedData.college.length;
console.log(collegeCount); // Outputs 2 for your sample data

Get the number of properties in a single college object:

For plain objects, use Object.keys() to convert the object's keys into an array, then get that array's length:

const firstCollege = parsedData.college[0];
const collegePropertyCount = Object.keys(firstCollege).length;
console.log(collegePropertyCount); // Outputs 7 for your first college (id, name, etc.)

2. "TypeError: Cannot convert undefined or null to object"

This error pops up when you try to run operations like Object.keys() or access length on a value that's undefined or null. Common causes in your case:

  • Your JSON failed to parse (so parsedData is undefined or an error).
  • The college array doesn't exist in your parsed data (so parsedData.college is undefined).
  • You're trying to access a college entry that doesn't exist (e.g., parsedData.college[2] which is undefined).

Fix with null/undefined checks:

Always validate your data before operating on it to avoid this error:

const parsedData = JSON.parse(yourJsonString);

// Check if parsedData exists and college is an array
if (parsedData && Array.isArray(parsedData.college)) {
  console.log(`Total colleges: ${parsedData.college.length}`);

  // Loop through each college and validate it's a valid object
  parsedData.college.forEach((college, index) => {
    if (typeof college === 'object' && college !== null) {
      const propCount = Object.keys(college).length;
      console.log(`College ${index + 1} (${college.name}) has ${propCount} properties`);
    } else {
      console.log(`College ${index + 1} is invalid (null/undefined)`);
    }
  });
} else {
  console.log('Invalid data: college array not found or data is malformed');
}

Quick Recap

  • Use array.length for arrays (like your college list).
  • Use Object.keys(obj).length for counting properties in plain objects.
  • Always add null/undefined checks to avoid the TypeError—never assume your data structure is exactly as expected!

内容的提问来源于stack exchange,提问作者miserable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:16:27