load google sheet data into json string with jquery
Just discovered this the other day, you can actually export google sheets data into json format and load it directly into your site, how good is that. A free mini basic database!
Initially i was looking into ways to store json data easily, so that i dont have to manually write the data and have an easy way of adding and removing data. This seems like a good solution.
Here is what you need to do:
-
Go to sheets.google.com and create a new blank sheet
- Add some kind of data
-
Publish the Sheet to the Web: File / Publish to the Web
-
Copy the key looking part of the Link, like this: 1BfQlexhe9K1HjkBbSZpcrEEjJsS9FRn3DFh_Uo_gY3k
Here is my test url, the bolded bit is the key you can paste into the box below to generate your link: https://docs.google.com/spreadsheets/d/1BfQlexhe9K1HjkBbSZpcrEEjJsS9FRn3DFh_Uo_gY3k/edit#gid=0
-
Paste it into here to generate the json link
Google Sheets JSON URL Generator
- Now you have a fully working json data feed for your page.
- Load it in with jquery and show the data
-
$.getJSON("https://spreadsheets.google.com/feeds/list/1BfQlexhe9K1HjkBbSZpcrEEjJsS9FRn3DFh_Uo_gY3k/od6/public/values?alt=json", function(data) { //also note that it will get rid of spaces in titles so "A Price" becomes "aprice" so better to use one word console.log(data.feed.entry[0]['gsx$titleone']['$t']); });
- Check the console and you should see some kinda data from the sheet
- Note: if new data is not showing up you will need to add the ajax no cacge to your doc ready.
If you check the console log it will show the text "Data One
"
HTML
<p class="codepen" data-height="265" data-theme-id="light" data-default-tab="js,result" data-user="kruxor" data-slug-hash="BazNrwr" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Test JSON Google Sheets">
<span>See the Pen <a href="https://codepen.io/kruxor/pen/BazNrwr">
Test JSON Google Sheets</a> by Luke (<a href="https://codepen.io/kruxor">@kruxor</a>)
on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
Javascript
$.getJSON("https://spreadsheets.google.com/feeds/list/1BfQlexhe9K1HjkBbSZpcrEEjJsS9FRn3DFh_Uo_gY3k/od6/public/values?alt=json", function(data) {
//also note that it will get rid of spaces in titles so "A Price" becomes "aprice" so better to use one word
//console.log(data.feed.entry[0]['gsx$titleone']['$t']);
console.log(data);
});
See the Pen Test JSON Google Sheets by Luke (@kruxor) on CodePen.