2017-03-01 141 views
0

我想從返回的JSON字符串中獲取鍵/值對;基於我的嘗試,我做錯了什麼?正確解析JSON數據

$(document).ready(function(){ 
    var json_url = "http://hudsonspine.com/ldn/ldn.json"; 
    var json_str = $.getJSON(json_url); 
    var json_strfy = JSON.stringify(json_str); 
    var json_to_obj = $.parseJSON(json_str); 
    console.log(json_to_obj.animal); 
}); 

我得到以下錯誤(這我假設手段無法正確格式的數據,即使我的JSON源似乎OK):

"jQuery.Deferred exception: Unexpected token o in JSON at position 1" "SyntaxError: Unexpected token o in JSON at position 1 
    at Function.parse [as parseJSON] (<anonymous>) 
    at HTMLDocument.<anonymous> (pen.js:13:21) 
    at j (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:29948) 
    at k (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:30262)" undefined 
+2

'$ .getJSON(json_url);'是一個異步調用 - 所以你的下一行是在'getJSON'完成之前執行。 – tymeJV

+0

一旦你過去了整個異步問題,並找出如何$ .getJSON實際上工作 - 'json_str'實際上將是一個JavaScript對象 - 爲什麼你將它串起來 - 將它保存爲json_strfy?並顯然試圖解析一個JavaScript對象,使用jquery的低級parseJSON,將失敗 –

回答

2

$.getJSON不返回JSON結果。它是一個異步函數,結果傳遞給回調函數。它已經被解析(這是$.get$.getJSON之間的唯一區別),所以你並不需要使用的功能,如$.parseJSON

$.getJSON($json_url, function(result) { 
    console.log(result.animal); 
});