I have the follow JS code to get the response from an URL. My URL it's ok, I got the response that I want to show, but I don't know how to show the response in JSON format. I'll appreciate any help.
var id = '84337255-f472-4630-986d-487f22009536';
var startDate = '2017-01-01';
var endDate = '2017-03-30';
var url = 'http://34.209.24.195/facturas\?id\=' + id + '\&start\=' + startDate + '\&finish\=' + endDate;
var urlRequestTimeout = setTimeout(function() {
console.log("Failed to load resources");
}, 8000);
$.ajax({
url: url,
dataType: "json",
method: "GET",
success : function(response) {
console.log(response);
clearTimeout(urlRequestTimeout);
}
});
You can use the chrome console to view the response you are printing. Without seeing what the output is, I can only make a guess.
I would do something like this
let jsonObj = {}; //create empty JSON variable
$.ajax({
url: url,
dataType: "json",
method: "GET",
success : function(response) {
console.log(response);
jsonObj = response.data; //set the variable to the response data
clearTimeout(urlRequestTimeout);
}
});
Now you have the response saved, and you can do with it what you want. If you want a more specific answer, you'll have to post your response output.
Or, as others have suggested. You can convert the value to a JSON string like such:
let jsonObj = JSON.stringify(response.data)
console.log(jsonObj);
Use
console.log(JSON.stringify(response.data));
instead of
console.log(response);
What you received is a json format.
I think there are methods to resolve 1. JSON.parse()
2. eval("(" + response + ")")
but the second method will run code in the json.(not safe)
json format:var data='{
"student" : [
{"name":"A","age":17},
{"name":"B","age":17},
{"name":"C","age":17}
]
}'
eval('(' + data + ')');//jsonString->jsonObject
JSON.parse(data);//jsonString->jsonObject