So I have data in JSON format from the Guardian API’s open platform I would like to parse this in jquery and I currently stuck trying to display results onto my HTML div.
The format of the data is as follows: Guardian JSON results
My code that I am trying to work with is as follows
function processFootballData(footballData){
footyStuff = footballData;
var thisContainer = document.getElementById( "results" );
var listTmp = document.createElement( "ul" );
var tmpList = "";
for( var i=0; (i<footyStuff.results[0].length) && (i<100); i++ ) {
if( tmpList.length <= 0 ) {
tmpList = footyStuff.results[0][ i ];
}
else {
tmpList = tmpList + "," + footyStuff.results[0][ i ];
}
}
var footballURL = "http://content.guardianapis.com/search?q=football&format=json&api-key=ky5zy8mds5r25syu36t9kmzj";
$.getJSON( footballURL,
function( thisData ) {
var data = thisData;
for( var key in data ) {
var thisSublist = document.createElement( "ul" );
thisSublist.setAttribute('style', "border-bottom: 1px solid #000; width: 80%;");
var thisItem = document.createElement( "li" );
var footyResults = data[key].results[0];
if( data.hasOwnProperty( key ) ) {
var duyList = document.createElement("li");
duyList.setAttribute('style', "padding-bottom: 10px;margin-top:-15px;margin-left:53px;font-size:12px;");
duyFooty = document.createTextNode(footyResults);
duyList.appendChild(duyFooty);
thisItem.appendChild(duyList);
}
thisItem.appendChild( thisSublist );
}
listTmp.appendChild( thisItem );
}
thisContainer.appendChild( listTmp );
});
}
You need to use a
jsonprequest, because the Guardian API is blocking cross-domain requests. Use the JQuery.ajaxwithdataType: jsonp:Your DOM-generation Javascript is a bit of a mess … but it’s easy to get lost writing that kind of code. I’d strongly recommend using some kind of micro-templating engine to handle the data-to-HTML conversion stuff.
Here’s an example of how to do this using Mustache.js.
Here’s the same example using Underscore.js. Same idea, but different implementation that lets you write the template as markup:
And the script to render: