Reputation: 317
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 view
But if I try to log data.text, data.responseText, or anything like that I just get undefined. How do I get the data?
Upvotes: 3
Views: 214
Reputation: 37701
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>
Upvotes: 3