Getting JSON data correctly

So, this is my first time working on jQuery. 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 magazine: object view <img src = "https://i.stack.imgur.com/MunsT.png" alt = "enter image description here">

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

+3


source to share


1 answer


The problem is what is console.log

done before data = JSON.stringify(data)

, because the call is $.getJSON

asynchronous.

This means that what you see in the console is not the object you receive in your callback.

To get the correct view 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 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>
      

Run codeHide result


+3


source







All Articles