Search code examples
javascriptjqueryjsongetjson

Properly parsing JSON data


I would like to get the key/value pairs from a returned JSON string; based on my attempt, what am I doing wrong?

$(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);  
});

I get the following error (which I'm assuming means not properly format data, even though my JSON source seems 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

Solution

  • $.getJSON doesn't return the JSON as a result. It's an asynchronous function, and the result is passed to the callback. It's already parsed (that's the only difference between $.get and $.getJSON), so you don't need to use functions like $.parseJSON

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