0

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');
              }
          });
3

1 Answer 1

1

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

1 Comment

no need to parse if you use dataType argument or just use $.getJSON

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.