Nag
Nag

Reputation: 956

Check if Key Value exists in JSON data

I want to know if the key-value pair exists in JSON data while retrieving data. Display "NA" inside div element if not present or else display the value of that key.

HTML:

   <div id="output"></div>

jQuery:

     $.get('http://api.fixer.io/2000-02-03',function(person){
         if(person.hasOwnProperty('rates.BGN'))  {
              $('#output').text(person.rates.BGN);
            }
         else  {
              $('#output').text('NA');
              }
          });

Upvotes: 0

Views: 704

Answers (1)

Dexygen
Dexygen

Reputation: 12561

First, you need to parse person into JSON.

Secondly you are misusing hasOwnProperty, it cannot be used to drill down into an object more than one level the way you are trying.

Finally hasOwnProperty is just unnecessary -- just test for existence as follows:

 $.get('http://api.fixer.io/2000-02-03',function(person){
     person = JSON.parse(person); 
     if(person.rates.BGN !== undefined)  {
          $('#output').text(person.rates.BGN);
     }
     //etc.

Upvotes: 1

Related Questions