Node.js中获取JSON对象长度报错:无法获取长度及TypeError求助
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
lengthproperty, but plain objects (like each individualcollegeentry in your array) do not. - In your data,
collegeis 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
parsedDataisundefinedor an error). - The
collegearray doesn't exist in your parsed data (soparsedData.collegeisundefined). - You're trying to access a college entry that doesn't exist (e.g.,
parsedData.college[2]which isundefined).
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.lengthfor arrays (like yourcollegelist). - Use
Object.keys(obj).lengthfor 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

