Created
October 17, 2012 18:53
-
-
Save mojowen/3907372 to your computer and use it in GitHub Desktop.
Functions for Retrieving Google Spreadsheet Data via JSONP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
API DOC: https://developers.google.com/google-apps/spreadsheets/ | |
Some things to remember: | |
- Get the Sheet ID "gid" by using the https://developers.google.com/google-apps/spreadsheets/#retrieving_information_about_worksheets | |
- Google API cannot handle spaces in it's SQL queries - make sure to wrap queries in " (not ') | |
- Column A is a "label" column - cannot query on it. Hide it | |
- Google returns results row contents a comma separated cell - googleParse function can convert into an object - including cell contents with commas. Cells with ': ' (including the space) may break it. | |
**/ | |
// Example function that will take a given GID (i.e worksheet) and a given lookup and write the array results to an observable | |
function ajaxCounty(lookup,gid,observable) { | |
return $.ajax({ | |
url: 'https://spreadsheets.google.com/feeds/list/0Ak0dQzYXW9EidGk5TkFHanJVMVp0Y0NfMy1PV3F2aVE/'+gid+'/public/basic?alt=json-in-script&callback=?', | |
data:'sq=county%3d'+loopup, | |
dataType:'jsonp', | |
success: function(r){ | |
if( r.feed.entry ) observable( $.map(r.feed.entry, function(el) { | |
for( var i in el.content ) { | |
if( i != 'type' && typeof el.content[i] == 'string' ) return processGoogleContent(el.content[i]); | |
} | |
})); | |
} | |
Running through a list of requests - adding request to AJAX queue - running function when queue complete | |
ajaxReqs = [] | |
for( var i =0 ; i < gets.length; i++ ) { | |
ajaxReqs.push( ajaxCounty(gets[i][0], gets[i][1],gets[i][2] ) ) | |
} | |
$.when.apply($, ajaxReqs).then(function() { | |
alldone( false ); | |
}); | |
// Function for doing a better trim | |
function ultraTrim(string) { | |
var trimArray = string.split(' '), goodString = ''; | |
for(var i =0; i < trimArray.length; i++) { | |
if( trimArray[i].length > 0 ) goodString += trimArray[i]+' '; | |
} | |
return goodString.trim(); | |
} | |
// Function for processing Google strings | |
function processGoogleContent(gstring) { | |
var garray = gstring.split(','), gobject = {}, last = '' | |
for(var i=0; i < garray.length; i++ ) { | |
var gsplit = garray[i].split(': ') | |
if( gsplit.length > 1 ) { | |
var gkey = gsplit.shift().trim() | |
gobject[ gkey ] = ultraTrim( gsplit.join(', ').trim().replace(/\t/g,'').replace(/\n/g,', ').replace(/\r/g,', ') ) | |
last = gkey; | |
} else { | |
gobject[ last ] += ', '+ultraTrim( garray[i].trim().replace(/\t/g,'').replace(/\n/g,', ').replace(/\r/g,', ') ) | |
} | |
} | |
return gobject | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment