user1448371
user1448371

Reputation: 329

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.

Upvotes: 0

Views: 2457

Answers (2)

Nir Levy
Nir Levy

Reputation: 12953

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
}

Upvotes: 4

user1448371
user1448371

Reputation: 329

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.

Upvotes: 3

Related Questions