Search code examples
javascriptarraysgoogle-visualizationgoogle-query-language

converting Google Visualization Query result into javascript array


The url to the spreadsheet I am querying is

docs.google.com/spreadsheets/d/1EIBhBQY1zbdBEKXsJIY1uyvdQw0b1cIBSrBE_tZvA6Y/edit?usp=sharing

The query url being used is

https://spreadsheets.google.com/tq?tqx=out:&key=1EIBhBQY1zbdBEKXsJIY1uyvdQw0b1cIBSrBE_tZvA6Y&gid=0&headers=1&tq=select%20B%2CC%2CD%20where%20(A%20matches%20%22DIS%22)

Is there a way to convert or store this result in a JavaScript array?

var dis = ["The Walt Disney Company","Entertainment",.1]

I need to be able to manipulate the data at one point and add the new data to the visualization.

Data from one of multiple queries --> Convert to array --> Manipulate data ex: multiplying an input --> data.addRows(manipulated input);


Solution

  • Your query does return a string containing JSON wrapped in a function call:

    var responseText = 'google.visualization.Query.setResponse({…});';
    

    This is because you specified out: as an argument for tqx (see Google Developers guides).

    If you want it all raw, you can extract and parse the JSON of multiple queries and push the data to an array, so you end up with an array of arrays of row data. For your single query, you could start from something like this:

    responseJSON = JSON.parse(
    responseText.replace(/(^google\.visualization\.Query\.setResponse\(|\);$)/g,'')
    );
    var rowsArray = [];
    responseJSON.table.rows.forEach(function(row){
        var rowArray = [];
        row.c.forEach(function(prop){ rowArray.push(prop.v); });
        rowsArray.push(rowArray);
    });
    console.log(rowsArray); // ===  [["The Walt Disney Company", "Entertainment", 0.1]]