Jon Jon - 3 months ago 9
jQuery Question

Build and prettify JSON object

I'm attempting to build a JSON object using ajax requests, then print out the data all prettified so it's easy to read.

Here's what I have:

var url, data;
var shows = ["stranger things", "the night of"];
var json = {};

$.each(shows, function(i, show) {
url = 'https://www.omdbapi.com/?t=' + show + '&type=series&plot=short'
$.ajax(url, {
complete: function(obj, status){
data = $.parseJSON(obj.responseText);
json.push(obj.responseText);
console.log(data);
}
});
});

var jsonPretty = JSON.stringify({shows: json}, null, '\t');
$("pre").text(jsonPretty);


https://jsfiddle.net/we1p7cqj/1/

The issue lies somewhere around
json.push(obj.responseText)
, but I can't figure out a fix.

Any ideas?

Answer

First of all you have the object initialization wrong: should be var json = [];

Also, since the ajax requests are asynchronous by default, the following code is executed at the same time, and at that time the value of json is empty object

var jsonPretty = JSON.stringify({shows: json}, null, '\t');
$("pre").text(jsonPretty);

So you can either make the ajax requests synchronous or check for the last show before you execute that code:

if(showsLength == i + 1){
    var jsonPretty = JSON.stringify({shows: json}, null, '\t');
    $("pre").text(jsonPretty);
}

Demo: https://jsfiddle.net/we1p7cqj/4/

HERE the other approach (synchronous requests)

$.ajax(url, {
    async: false,
    complete: function(obj, status){
      data = $.parseJSON(obj.responseText);
      json.push(obj.responseText);
      console.log(data);
    }
  });

Demo: https://jsfiddle.net/we1p7cqj/5/

Ah, I understand now. Thanks for the help, Sam! Is there a way to remove the slashes \"? – Jon 10 mins ago

The reason you see these slashed is because you are stringifying a string not an object, so to fix that you need to make it a json object when you push

data = $.parseJSON(obj.responseText);
json.push(data);

DEMO: https://jsfiddle.net/we1p7cqj/7/

Comments