2017-02-03 60 views
0

我想知道在檢索數據時鍵值對是否存在於JSON數據中。 如果div元素不存在,則顯示「NA」,否則顯示該鍵的值。檢查JSON數據中是否存在鍵值

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

恰恰是什麼問題? – lonesomeday

+0

將'json'解析爲javascript對象,然後'hasOwnProperty'將起作用。 'var res = JSON.parse(person);' – Ashot

+1

[將JavaScript表達式中的JavaScript字符串轉換爲對象引用]的可能重複(http://stackoverflow.com/questions/6393943/convert-javascript-string-in- dot-not-to-an-object-reference) –

回答

1

首先,你需要分析人成JSON。

其次,您正在濫用hasOwnProperty,它不能用於以您嘗試的方式在一個以上的級別鑽取對象。

最後hasOwnProperty僅僅是不必要的 - 只是測試存在如下:

$.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. 
+0

如果使用dataType參數或僅使用'$ .getJSON',則不需要解析 – charlietfl