After getting an HTTP response in the form a JSON file, how can I handle its plain content using jQuery?
I've done this before, but I just can't figure out how right now.
I'm using this function to retrieve the JSON content.
var json = $.getJSON("test.json",
function(response){
// do stuff
}
);
Of course, I can handle the data contained in the JSON, but I'd like to handle and print its plain content, like this:
{"name": "Pepe","age" : "20"}
The following
alert(response);
Just gives me [object Object]
And this
alert(jQuery.parseJSON(json));
Just gives me null
I can't seem to find the answer anywhere. I'm pretty new to all this, so I must be using the wrong search terms, because it looks like a trivial matter.
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
JSON.stringify
is probably what you want. MDN Docs
The callback to $.getJSON
actually has 3 parameters. data
, textStatus
and jqXHR
.
The jqXHR
object contains a responseText
property that contains the raw JSON string.
var json = $.getJSON("test.json",
function(response, status, jqXHR){
// do stuff
console.log(jqXHR.responseText);
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With