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
'$ .getJSON(json_url);'是一個異步調用 - 所以你的下一行是在'getJSON'完成之前執行。 – tymeJV
一旦你過去了整個異步問題,並找出如何$ .getJSON實際上工作 - 'json_str'實際上將是一個JavaScript對象 - 爲什麼你將它串起來 - 將它保存爲json_strfy?並顯然試圖解析一個JavaScript對象,使用jquery的低級parseJSON,將失敗 –