GoogleAPI/JSON: Retrieving data from spreadsheet? - javascript

It turns out that I came up with my own solution:
var data = {"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gs":"http://schemas.google.com/spreadsheets/2006","xmlns$batch":"http://schemas.google.com/gdata/batch","id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"Sheet1"},"link":[{"rel":"alternate","type":"text/html","href":"https://spreadsheets.google.com/pub?key\u003d0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE"},{"rel":"http://schemas.google.com/g/2005#feed","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic"},{"rel":"http://schemas.google.com/g/2005#batch","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/batch"},{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic?alt\u003djson-in-script"}],"author":[{"name":{"$t":"dhuanco"},"email":{"$t":"dhuanco#gmail.com"}}],"openSearch$totalResults":{"$t":"9"},"openSearch$startIndex":{"$t":"1"},"entry":[{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C1"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"A1"},"content":{"type":"text","$t":"Maria"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C1"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C2"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"B1"},"content":{"type":"text","$t":"30"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C2"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C3"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"C1"},"content":{"type":"text","$t":"USA"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C3"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R2C1"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"A2"},"content":{"type":"text","$t":"John"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R2C1"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R2C2"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"B2"},"content":{"type":"text","$t":"32"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R2C2"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R2C3"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"C2"},"content":{"type":"text","$t":"ENG"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R2C3"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R3C1"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"A3"},"content":{"type":"text","$t":"Susan"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R3C1"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R3C2"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"B3"},"content":{"type":"text","$t":"25"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R3C2"}]},{"id":{"$t":"https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R3C3"},"updated":{"$t":"2012-10-11T21:56:33.189Z"},"category":[{"scheme":"http://schemas.google.com/spreadsheets/2006","term":"http://schemas.google.com/spreadsheets/2006#cell"}],"title":{"type":"text","$t":"C3"},"content":{"type":"text","$t":"GER"},"link":[{"rel":"self","type":"application/atom+xml","href":"http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R3C3"}]}]}};
function format_ss(data){ // format spreadsheet
var table = new Array();
for(var k in data.feed.entry){
var id = data.feed.entry[k].id.$t;
var row = id.match(/R([0-9]*)C/)[1]-1;
var col = id.match(/C([0-9]*)/)[1]-1;
if(Object.prototype.toString.call(table[row]) != '[object Array]')
table[row] = new Array();
table[row][col] = data.feed.entry[k].content.$t;
}
return table;
}
var ss = format_ss(data);
It worked like a charm.
Original Question:
This is a public spreadsheet I created using google docs:
https://docs.google.com/spreadsheet/pub?key=0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE&output=html
My problem is, how can I properly get this data with JSON?
I tried
http://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic?alt=json-in-script&callback=test
This is awful to work with. The json data doesn't come properly formatted, for example I can't exactly tell what cell belongs to which column/field.
Does anyone know a better way to fetch this spreadsheet data?

If you look under the "Entry" section you'll see:
"id": {
"$t": "https://spreadsheets.google.com/feeds/cells/0ArzGbN1Jn061dFdJZ29VcWttZExoRXQ5TnZVX29xUlE/od6/public/basic/R1C1"
}
The ID is basically the URL of Row 1, Column 1. Then under that you'll find the:
"content": {
"type": "text",
"$t": "Maria"
}
The $t value there should give you your data. I have to agree it's a bit verbose but that's the nature of something that has so many properties.

Related

How to parse dynamic json data?

I am using wikipedia API my json response looks like,
"{
"query": {
"normalized": [
{
"from": "bitcoin",
"to": "Bitcoin"
}
],
"pages": {
"28249265": {
"pageid": 28249265,
"ns": 0,
"title": "Bitcoin",
"extract": "<p><b>Bitcoin</b>isapeer-to-peerpaymentsystemintroducedasopensourcesoftwarein2009.Thedigitalcurrencycreatedandlikeacentralbank,
andthishasledtheUSTreasurytocallbitcoinadecentralizedcurrency....</p>"
}
}
}
}"
this response is coming inside XMLHTTPObject ( request.responseText )
I am using eval to convert above string into json object as below,
var jsonObject = eval('(' +req.responseText+ ')');
In the response, pages element will have dynamic number for the key-value pair as shown in above example ( "28249265" )
How can I get extract element from above json object if my pageId is different for different results.
Please note, parsing is not actual problem here,
If Parse it , I can acess extract as,
var data = jsonObject.query.pages.28249265.extract;
In above line 28249265 is dynamic, This will be something different for different query
assuming that u want to traverse all keys in "jsonObject.query.pages".
u can extract it like this:
var pages = jsonObject.query.pages;
for (k in pages) { // here k represents the page no i.e. 28249265
var data = pages[k].extract;
// what u wana do with data here
}
or u may first extract all page data in array.
var datas = [];
var pages = jsonObject.query.pages;
for (k in pages) {
datas.push(pages[k].extract);
}
// what u wana do with data array here
you can archive that using two methods
obj = JSON.parse(json)
OR
obj = $.parseJSON(json);
UPDATE
Try this this
var obj = JSON.parse("your json data string");
//console.log(obj)
jQuery.each(obj.query.pages,function(a,val){
// here you can get data dynamically
var data = val.extract;
alert(val.extract);
});
JSBIN Example
JSBIN

How to create JSON object in jquery by getting values through iteration

I am new to JSON and jquery. I have the following use-case for which I need some help.
I need to create an array of objects in the following format:
{ "endpoint" : [
{ "ip": "16.140.23.90", "mac": "a2:35:67:e7" },
{ "ip": "16.140.23.91", "mac": "36:b1:79:ab" }
]
}
This is a sample of what I need (representing two rows only, there can be more). Now the value of ip and mac I need to add by iterating over a table's selected rows.
E.g. there is a table on the GUI in which each row is having two columns "IP" and "MAC". I need to get the data of the selected rows in the above format.
How do I form the JSON array in the above format when I need to add the values of the attributes while iterating? Anything I can do using JSON.stringify API? If yes, then how do I form the string which I can pass to JSON.stringify which results in the above format?
Any help will be highly appreciated.
If this is your table (first cell is ip and 2nd cell is mac)
<table id='tbl'>
<tr><td>16.140.23.90</td><td>a2:35:67:e7</td></tr>
<tr><td>16.140.23.91</td><td>36:b1:79:ab</td></tr>
</table>
Pure JS
var ips = { "endpoint" : [] };
var tbl = document.getElementById('tbl');
for (var i=0; i<tbl.rows.length; i++) {
ips["endpoint"].push({
"ip" : tbl.rows[i].cells[0].innerHTML,
"mac" : tbl.rows[i].cells[1].innerHTML
});
}
Fiddle
jQuery
var ips = { "endpoint" : [] };
$(document).ready(function() {
$('#tbl tr').each(function(i) {
ips["endpoint"].push({
"ip" : $(this).find('td:eq(0)').text(),
"mac" : $(this).find('td:eq(1)').text()
});
});
var json = (JSON.stringify(ips));
document.getElementById('json').innerHTML = json;
});
Fiddle
The first answer is good. But since this question is in regard to jquery, I provide a similar solution using jquery to manipulate the DOM.
The table is still the same:
<table id='tbl'>
<tr><td>16.140.23.90</td><td>a2:35:67:e7</td></tr>
<tr><td>16.140.23.91</td><td>36:b1:79:ab</td></tr>
</table>
The javascript code to creat the json object:
var ips = { "endpoint": [] };
var rows = $('#tbl tr');
for (var i = 0; i < rows.length; i++) {
ips["endpoint"].push({
"ip": rows.eq(i).find("td").eq(0).text(),
"mac": rows.eq(i).find("td").eq(1).text()
});
}
Fiddle
JSON is just a serialized representation of javascript objects, so just make the objects in javascript and then serialize using the JSON.stringify method. If you're not sure how to make a javascript object and add values to an array, then you should do a little googling, since that's pretty basic stuff.

Load JSON array from a database SQLITE

I have the following code in an array for Javascript JSON:
params = {
"fighters": [
{
"name": "Muhammad Ali",
"nickname": "The Greatest"
},
{
"name": "Chuck Liddell",
"nickname": "The Iceman"
}
]
};
Now I have "N" variable data "name" and "nickname" from a database SQLITE.
The idea is to show all the "nick" and "nickname" that exist from the database iteratively.
How I can fill it?
I tested with a FOR that runs all the arrangements and I charge them, for it did something like this:
params = {
"fighters": [ show[i] ]
};
It does not work.
I hope I explained correctly.
Thanks.
That will retrieve all fighters names:
var len = params.fighters.length;
for (var i = 0; i < len; i++) {
console.log( params.fighters[i].name );
}
To change fighters names values do the following:
var len = params.fighters.length;
for (var i = 0; i < len; i++) {
params.fighters[i].name = 'Your_Fighter_Name';
}
Hopefully i have helped you.
assuming we're in the fetchAll(function (error, rows) {}) callback using node-sqlite (meaning rows is an array of objects, with the keys in the objects being the column names):
var params = { "fighters" : [] };
rows.forEach(function (row) {
params.fighters.push({name: row.name, nickname: row.nickname});
});
Remember, JSON is subset of JS, it is not it's own language. It's NOT a programming language. You can't "do" anything in JSON, as it is not a programming language. You can't iterate, recurse, fill... you can do that with JS.
Sorry for repeating myself, but apparently a lot of people mistake JSON for something it isn't. I'm not assuming you do, but it can't be said too often ;-) How you want to send the JSON I can't tell you, as there is no information in your question. If you want to do this via a byte-based protocol such as HTTP you might want to use JSON.stringify() to get a textual representation of your object that you can send over the network.
See my version of your fiddle: http://jsfiddle.net/dpL4c/2/ .

Highcharts with multiple series from JSON

After reading and testing since few days (And already post here but with a wrong question) I really need you because I fail again and again...
My goal : having many series on same charts (and many charts in the future)
My data source : a mysql and a json output :
"[{"name":"Station 1","data":"1360191600,398.625"},{"name":"Station 1","data":"1360192500,398.625"},{"name":"Station 1","data":"1360193400,398.25"},{"name":"Station 1","data":"1360194300,397.375"},{"name":"Station 1","data":"1360195200,397.5"},{"name":"Station 1","data":"1360196100,397.5"},{"name":"Station 1","data":"1360199700,396.75"},{"name":"Station 1","data":"1360200600,397"}...
These data are an example because in normal time I have many station and some with only the timestamp data.
My big fail at this moment is to send these information to the series:[] option.
I have try some loops like this :
data=JSON.parse(data) ;
var series = [];
series.data = [];
$.each(data,function(i,ligne) {
var string = JSON.stringify(ligne);
var obj = $.parseJSON(string);
//var index_serie = obj.name.slice(0,1) ;
console.log(obj) ;
points=(obj.data) ;
series.name=obj.name ;
series.data.push(points) ;
}) ;
options.series.push(series) ;
console.log(options.series) ;
var chart = new Highcharts.Chart(options);
The options of the chart are defined before the ajax call.
I have try with a other format of json like ["name":"station1","data":"[1321654,10],[5465... but I have difficulties to add the [] in my sql quesry and the GROUP_CONCAT have some limitation (2014 character)
So help me to create a nice loop in order to render multiple series with their name etc
Thanks for your help...
Can't you change that "almost" JSON to "another" JSON? Maybe something like this:
[{
"name":'station 1',
"data": [ [360191600,398.625], [360191600,398.625], [360191600,398.625] ... [360191600,398.625] ]
}, {
"name":'station 2',
"data": [ [360191600,398.625], [360191600,398.625], [360191600,398.625] ... [360191600,398.625] ]
}]
If not, you have to add some parsing for your values, example:
data = JSON.parse(data);
var names = [];
$.each(data, function (i, ligne) {
var ind = names.indexOf(ligne.name),
splited = ligne.data.split(','),
x = parseFloat(splited[0]),
y = parseFloat(splited[1]);
if (ind == -1) {
/*series name spotted first time need to add new series */
ind = names.push(ligne.name) - 1;
options.series.push({
data: [],
name: ligne.name
});
}
if(!isNaN(x) && !isNaN(y)){
options.series[ind].data.push([x,y]);
}
});
And working jsfiddle: http://jsfiddle.net/3bQne/40/

Create JSON from jQuery each loop

All the questions I have dug through in the boards aren't really answering a question I have. So I will ask the experts here. First off, thank you very much for reading on. I really appreciate what Stackoverflow is all about, hopefully I can contribute now that I am a member.
I want to dynamically create a JSON object based off variables set from another JSON object from with a jQuery each loop. I think my syntax and probably my knowledge of this stuff is a little off.
I would like to end up with the following JSON structure:
{
desktop:{
title:300,
rev:200
}
}
Where "desktop" is a value from another JSON object not in this loop, I can call that no problem, in fact it is actually the name value I set on the other JSON object. I am looping through an array in the object called columns but want to set a separate object containing all the widths because the columns are adjustable and accessible via another frame that I will push it to, I want to retain those widths.
I was trying to do this from within the loop:
var colWidths = {};
$.each(columns, function(i) {
colWidths.desktop.title = columns[i].width;
});
I can alert columns[i].width successfully. The issue I have is creating and accessing this. Everything I seem to be doing seems right but this is not the case. Maybe its me or my setup? Could you please show me how to code this properly? OR I could create a Javascript Object if this is not possible. Thanks in advance!
Welcome to Stackoverflow. You did not write any error messages you got, so I assume the following.
// prepare the object correctly first
var colWidths = {
desktop: {
title: 0
}
};
// then ADDING each value with += instead of =
// (because in your code you will just have the last value)
$.each(columns, function(i) {
colWidths.desktop.title += columns[i].width;
});
EDIT
var grid = {
"name": "desktop",
"columns": [
{
"id": "icons",
"width": 50},
{
"id": "title",
"width": 200},
{
"id": "name",
"width": 300},
{
"id": "revision",
"width": 400}
]
};
var columns = grid.columns;
var gridName = grid.name;
var colWidths = {};
// CHANGE HERE
colWidths[gridName] = {};
$.each(columns, function(c) {
var col = columns[c];
var colname = col.id;
var colwidth = col.width;
// CHANGE HERE
var thisGrid = colWidths[gridName];
if(!thisGrid[colname]) thisGrid[colname] = 0;
thisGrid[colname] += colwidth;
});
//alert(colWidths.desktop.title);​
document.write(JSON.stringify(colWidths));
// RESULT:
// {"desktop":{"icons":50,"title":200,"name":300,"revision":400}}

Categories

Resources