jack gallerdude galler jack gallerdude galler - 4 months ago 24
jQuery Question

Grabbing JSON data properly

So I'm working on jQuery for the first time. When I use this:

var data = $.getJSON("https://hackernews.firebaseio.com/v0/item/14279870.json", function(data) {
data = JSON.stringify(data)
});
console.log(data);


I get this guy in the log: object viewenter image description here

But if I try to log data.text, data.responseText, or anything like that I just get undefined. How do I get the data?

Answer Source

The problem is that console.log executes before data = JSON.stringify(data) because $.getJSON call is asynchronous.

That means that what you see in the console is not the object that you get inside your success callback.

To get a proper representation of your data object (after the server call), put the console log inside the callback function:

$.getJSON("https://hackernews.firebaseio.com/v0/item/14279870.json", function(data) {
    console.log(data);
    data = JSON.stringify(data)
    console.log(data);
  });

Live example with a sample JSON file (your URL returns null):

$.getJSON("http://echo.jsontest.com/key/value/one/two", function(data) {
        console.log("JSON: ", data);
        data = JSON.stringify(data)
        console.log("Stringified: ", data);
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>