0

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.

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

4 Comments

try/catch is a bit expensive here if you can simply check if it exists
I tried to do check if, but it shows me the same error even if I use check if.
BTW, may I know what you mean by "try/catch is a bit expensive", please?
what it means is that when using try/catch what happens is that it fails, has to generate an error object (with stack and more details) and throw it for you to catch. This is more expensive to do in runtime than simply check existence

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.