0

I'm parsing some JSON with jQuery into array. So there is a place where i'm assigning this:

$("#address_text").text(data['account']['address']['text']);

The problem is that sometimes i don't have this in the JSON and i've got error:

TypeError: null is not an object (evaluating 'data['account']['address']')

And the script is blocked under that line.

Is there anyway that i can ignore the error and assign nothing to #address_text ? I search something like "@" sign in php. That no matter what is the error, just ignoring it.

Nicox
  • 83
  • 3
  • 11
  • 1
    I would always argue against just ignoring errors. It would be better to check the inputs if you are not sure about their contents. A simple `if`-statement would suffice. Or use a `try-catch`-construction. – Bart Barnard Jun 09 '20 at 20:07
  • i tried `data['account']['address']['text']?data['account']['address']['text']:""` but it didn't worked out :( – Nicox Jun 09 '20 at 20:09
  • Javascript fails to exist with error. Basically it's impossible to ignore especially critical error like empty value to parse function – Yotam Dahan Jun 09 '20 at 20:20
  • @HereticMonkey Good examples, I tried the last one `data.account?.address?.text?` but it does not work (yet?) – Nicox Jun 09 '20 at 20:40
  • What browser? [The feature is available in the recent versions of most browsers](https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining) but, IE won't ever get it. Also, you might want to use `data?.account?.address?.text` in case `data` is null/undefined. – Heretic Monkey Jun 09 '20 at 20:43
  • @HereticMonkey Oh, i'm with Safari 12, So, yeah. its because the browser. Well, it's not what i was looking for, but it something that i can accept as a workaround. And i will hope everybody using it are with the newest version of the browsers :) – Nicox Jun 09 '20 at 20:49

2 Answers2

2

First: If you have an error, fix the error not ignore it.

Second: Check if value exist before get the property

if (data && data['account'] && data['account']['address'] && data['account']['address']['text']) {
....
}
Francisco
  • 1,748
  • 1
  • 17
  • 19
  • @Zaid abu khalaf I didn't call this error. For me its just missing information. The API is not under my control. I made just the handling script. – Nicox Jun 09 '20 at 20:18
0

How about this?

  if(data && data.account && data.account.address && data.account.address.text){
    $("#address_text").text(data['account']['address']['text']);
    }else{
     $("#address_text").text("data is not valid");
    }
ABGR
  • 4,631
  • 4
  • 27
  • 49