简体   繁体   中英

Check if json object is undefined in Node.js

I'm getting this error "TypeError: Cannot read property '0' of undefined" when I want to extract a data from JSON file.

However, the data I want to extract is not available every time I request a JSON file, therefore, I'm getting this error which makes my Node.js Application to crash every time I'm getting this error.

A solution for this sort of problem is using try-catch:

try {
  data = json['Name']['Nationality'][0];
} catch (error) {
  data = "Sorry no data found"
}

The try function is going to run the code if it did find any error it will pass it to catch.

simply check if it exists or not:

if (json && json['Name'] && json['Name']['Nationality']) {
  data = json['Name']['Nationality'][0];
} else {
  // no data, do whatever error handling you want here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM