Read & parse JSON response from API - javascript

I have an API endpoint like this:
https://client.systemonesoftware.com/bannink/json/?language=nl
I need to read and parse it into a table with all the information. But I get no output when I try to do it with Javascript.
<script>
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(data) {
var json = JSON.parse(data);
alert(json.cached);
alert(json.data[1].id);
});
</script>
This piece of code gives nothing..

$.getJSON returns JavaScript object so you don't need to parse it, try:
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(json) {
console.log(json.data[1].id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

I believe your issue is that the data already comes through parsed:
<script>
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(json) {
alert(json.cached);
alert(json.data[1].id);
});
</script>

Related

why use JSON.Parse(data) after ajax sucess?

I have this following code.
success: function(data) {
console.log(data) //everything
console.log(data['quote']); //undefined
var JSONObject = JSON.parse(data); //why parse again?
var quote =JSONObject['quote']
console.log(data['quote']); //returns quote
}
why do I need to parse the JSON object again even though the return from api call is already a JSON Object?
It seems the data returned from server is JSON string instead JSON object. If the data is string, you need to parse that string to javascript object.

How do you get responseText from jQuery.getJSON method in javascript?

I am trying to read in a JSON file from my directory using the jQuery.getJSON method and it returns the object shown in the picture. I want to get the responseText from the object but cannot figure out how.
var jsonData = jQuery.getJSON('relationalData.json');
Ive tried to use the following to extract the responseText but they all failed.
var response = jsonData.responseText;
var response = jsonData['responseText'];
I also tried using without any luck, as the method doesn't even get called with a json file. It worked when I used an xml though.
$.get(filename, function(data){
var responseText = data;
});
A similar solution to guest271314 but, maybe, still instructive for someone ...
$.getJSON('http://ws.spotify.com/search/1/artist.json?q=foo')
.done(function(obj,status,xhdr){$('#out').append(xhdr.responseText);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out"><div>
The important part is to look for the .responseText property in the xhdr object, which can be accessed though the third parameter of the callback function.
Came across this question which has been longed asked, but for future visitors where is my solution:
$.getJSON method fetches data from a server using HTTP GET request, the response on successful call returns in a responseText property as you see in your console.
Therefore to get the data of the responseText you have to use the JSON.parse() method to retrieve data to javaSrcipt object like this:
var jsonData = JSON.parse(jsonCall.responseText);
But $.getJSON() method is asynchronous so this must be done inside the callback function if not the response may not exist.
Final solution:
var jsonCall = $.getJSON('URL',function(){
var jsonData = JSON.parse(jsonCall.responseText);
console.log(jsonData);
});
Try utilizing .then() , substituting responseJSON for responseText
var jsonData = jQuery.getJSON("https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/a5ac6cffdc1ffab39f9db425844721b528751654/a.json");
jsonData.then(function(data, textStatus, jqxhr) {
alert(jqxhr.responseJSON)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

getting json data jquery with .get

<script>
$.get("url", function(data, textStatus, jqXHR) {
var json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
Hey,
I would like to get data from url. I can get the JSON file and stringify it to json variable. But I have some struggles when I 'm trying to use json variable. Because, it is local variable.
Also,
<script>
var json = "";
$.get("url", function(data, textStatus, jqXHR) {
json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
when I am trying to use json as a global variable, even I can not stringify data to it.
Question : How can I solve my problem?
It would be better to use your JSON data when it is available by putting the dependent code in a callback or a promise:
$.getJSON("url").then(function(data) {
// json is already parsed here
// put json dependent code here
});
You could also put your application logic in a function (assuming it's depending on the JSON data) and use that as your callback:
function initialize(data) {
// all of your data dependent logic here
}
$.getJSON("url").then(initialize);

Retrieve JSON encoded data in AJAX callback

This is the result when I do console.log(data) within my AJAX callback
{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}
but when I do data['image'] or data['url'], it can't retrieve the value correctly. I also tried data[0]['image'] to no avail
So I guess data is returned from a ajax request. Your can use the following code to convert string to object:
data = JSON.parse(data);
If you are using jQuery to do the ajax request, you can add dataType: "json" to the ajax option. In this way, there's no need to convert data.
Your data in callback is JSON Object,then
var image=data.image;
var url=data.url;
have you tried data.image and data.url?
also try var x = eval(data);
then x.image and x.url
Be careful of eval() on untrusted data though!!
You need to parse it to Json
var retrieved = ......;
var json = JSON.parse(retrieved);
and then just use:
var image = json.image;
var url = json.url;
Usualy this code from jQuery API's page works great:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
However, you must remember about the same origin policy as well as the about the correct server response's content type. For json response it should be application/x-javascript or at least text/json.
javascript does not have associative arrays, You should use a javascript object like
var data = JSON.parse(data)
and then you can acces it by
data.image and data.url
If You are getting string as a response then use like below.
var response = '{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}';
var data = eval("("+response +")");
console.log(data["image"]);
console.log(data["url"]);

Turning post request data into .each() function

I'm using this code
$.post("assets/scripts/chat/load_convos.php",{}, function(data) {
$.each(data, function(index, value) {
alert(value);
});
,and the return of the data is [57,49] but it just doesn't do anything... If I replace the data just after the $.each( with [57,49] it works but not with the data in its place.
I'm not the best with Javascript so all help is much appreciated.
What do you mean with "the data is [57,49]" ?
My guess is, that you expect a (JSON)-object but you just receive a string. My second guess is that jQuery interpretates the result the wrong way and does not identify the return as JSON-String and hence, does not implicit JSON.parse it.
Check the content-types of the request. Try to call data = JSON.parse(data); manually before calling the each loop. Actually jQuery should be able to identiy that string as a JSON result itself, so I'm also wondering which jQuery version you use.
Another shot you might have is to call .getJSON() instead of .post() directly.
You can use JSON.parse or eval('('+response+')'); but probably the solution is to specify to jQuery or the library you are using that the response is JSON.
By the way, no all browsers have the JSON object, so if your library don't provide it you'll have to use the eval solution.
Specify json as your datatype.
Taken from jquery.post documentation
Example: Posts to the test.php page and gets contents which has been
returned in json format
(<;?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");

Categories

Resources