Replace the contents in multiple JSON files based on their file name? - json

How to replace the contents in multiple JSON files based on their file name?
I have a certain number of description files and I need to sort their contents by file name.
For ex. files numbered 1.json, 2.json, ... 10.json
All files inside have the same object names, but different numbers
{
"name": "Garlic 8",
"position": 8,
"description": "Only for stuff.",
"external": "row five",
"image": "buffer/8.png",
"basic": [
{
"type": "row",
"value": "one"
},
{
"color": "pure",
"value": "no"
}
]
}
How to replace numbers in all files with numbers from file names?
(i.e. the numbers inside the file must match the file number)
const basePath = process.cwd();
const fs = require("fs");
const {baseUri, namePrefix,} = require(`${basePath}/src/config.js`);
for (
let i = 1;
i <= 10;
i++
)
{
let rawdata = fs.readFileSync(`${basePath}/rename/json/${i}.json`);
let data = JSON.parse(rawdata);
var originalMsg = JSON.stringify(data);
data.each(function(item) {
{
item.name = `${namePrefix} #${i}`;
item.position = `${i}`;
item.image = `${baseUri}/${i}.png`;
}
});
console.log(originalMsg)
console.log(data)
But typeError: data.each is not a function

Related

JSON File on Drive to Google sheets

I have a few JSON files on my Google Drive from which I need to extract data into a spreadsheet. I have tried the ImportJson function from github but that is to fetch the JSON file directly from the API but the JSON files I have on my drive are not accessible to me directly from the API.
Can anyone help me in how can I get the JSON stored on the drive to be imported in the Google sheets.
The sample JSON is attached herewith:
{
"gstin": "12ABCDE",
"fp": "082019",
"b2b": [{
"ctin": "2312ABCDEY",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 1072,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 81.76,
"rt": 18,
"txval": 908.48,
"camt": 81.76
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "02-08-2019",
"rchrg": "N",
"inum": "642",
"chksum": "7a58ec7342001040acf4509176ba22ceb03d9ad0ecf7e74d572af0ec4d8429fa"
}, {
"val": 1072,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 81.76,
"rt": 18,
"txval": 908.48,
"camt": 81.76
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "17-08-2019",
"rchrg": "N",
"inum": "722",
"chksum": "0597afa614e27aa78dc252f2530172007e574f52d1ceea9e433e04f474414bbf"
}],
"fldtr1": "10-Sep-19",
"flprdr1": "Aug-19"
}, {
"ctin": "22AAB1Z5",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 459463,
"itms": [{
"num": 1801,
"itm_det": {
"csamt": 0,
"rt": 18,
"txval": 389375,
"iamt": 70087.5
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "30-08-2019",
"rchrg": "N",
"inum": "2495",
"chksum": "15ef392cfd4fd3af2fce1ad8549f93bac20cf17308df9bf9256ae838db45a440"
}],
"fldtr1": "11-Sep-19",
"flprdr1": "Aug-19"
}, {
"ctin": "23AFEZI",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 9350,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 713.16,
"rt": 18,
"txval": 7924,
"camt": 713.16
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "02-08-2019",
"rchrg": "N",
"inum": "00075",
"chksum": "cb4fe40cb2f39f8782a160ece273991daae68b739dfba454ffeb364150d03580"
}, {
"val": 12312,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 939.07,
"rt": 18,
"txval": 10434.09,
"camt": 939.07
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "10-08-2019",
"rchrg": "N",
"inum": "00084",
"chksum": "1d0fa36c2a7f1ffe7d7c07a829056e4e28fd0300fd593f91ba8216ace4e54f2a"
}],
"fldtr1": "05-Sep-19",
"flprdr1": "Aug-19"
}, {
"ctin": "23ECVPSQ",
"cfs": "Y",
"cfs3b": "Y",
"inv": [{
"val": 10200,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 777.97,
"rt": 18,
"txval": 8644.1,
"camt": 777.97
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "13-08-2019",
"rchrg": "N",
"inum": "650",
"chksum": "43bcf7c73bf94013344111d95c6f80dea47980ef4bfd3093a33e2c385baa2fdd"
}, {
"val": 4745,
"itms": [{
"num": 1,
"itm_det": {
"csamt": 0,
"samt": 361.91,
"rt": 18,
"txval": 4021.18,
"camt": 361.91
}
}],
"inv_typ": "R",
"pos": "23",
"idt": "30-08-2019",
"rchrg": "N",
"inum": "727",
"chksum": "fae1037d879dc718f322e8622a5323344a6cf88b68f68620aaa7ed5d92a15a23"
}]
}
Data sample to look like this
You basically want to retrieve all the nested properties in your object (after you've converted the JSON string using JSON.parse(), and write the corresponding key-value pairs to the first two rows of your spreadsheet (key in row 1, value in row 2). When the value is an object, the key will be written in row 1, but row 2 will remain blank (e.g. b2b).
In this case, you could use recursion to iterate through and retrieve all the nested properties and values from the object. The function could be something like this:
function allProps(element, array, parent = "") {
if (typeof element === 'object' && element !== null) {
if (parent != "") array.push([parent, ""]);
const entries = Object.entries(element);
entries.forEach(entry => {
const nextParent = Array.isArray(element) ? "" : entry[0];
allProps(entry[1], array, nextParent);
});
} else {
array.push([parent, element]);
}
}
The idea is that, for each value, it checks if the value is an object or a primitive data type. If it's the former, allProps gets called recursively, and if it's the latter, the key-value pair is added to the spreadsheet.
And you could call it this way:
function JSON_to_Spreadsheet() {
const id = "JSON_FILE_ID"; // Change to your FILE_ID
const json = DriveApp.getFileById(id).getBlob().getDataAsString(); // Get JSON text from Drive file
const obj = JSON.parse(json); // JSON text to JS object
let array = []; // 2D array where the output will be stored
allProps(obj, array, parent = ""); // Call function recursively
array = array[0].map((_, colIndex) => array.map(row => row[colIndex])); // Transpose 2D array
const sheet = SpreadsheetApp.getActive().getActiveSheet(); // Retrieve active sheet. Change if you want to access another sheet or another spreadsheet
sheet.getRange(1,1,array.length, array[0].length).setValues(array); // Write 2D array to your sheet.
}
The output looks like this:
Edit:
If you want each ctin header (apart from the first one, in column D) to occupy a new row, you can do the following once you have retrieved the 2D array:
Retrieve an array with all the indexes from array[0] where the header is ctin (excluding the first one).
Using these indexes, add each ctin segment to the main array.
Write the array to the sheet, taking into account that the different rows have different lengths. If you wanted to use a single setValues (that would be recommended for efficiency purposes), you'd first have to find the maximum length of the inner array elements, and make all the inner arrays have this length.
The function JSON_to_Spreadsheet could be something like this:
function JSON_to_Spreadsheet() {
const id = "JSON_FILE_ID"; // Change to your FILE_ID
const json = DriveApp.getFileById(id).getBlob().getDataAsString(); // Get JSON text from Drive file
const obj = JSON.parse(json); // JSON text to JS object
let array = []; // 2D array where the output will be stored
allProps(obj, array, parent = ""); // Call function recursively
array = array[0].map((_, colIndex) => array.map(row => row[colIndex])); // Transpose 2D array
const ctinFirstIndex = 3; // Column D (first ctin)
const ctinIndexes = array[0].reduce((acc, current, i) => {
if (current === "ctin" && i !== ctinFirstIndex) {
acc.push(i);
}
return acc;
}, []); // Find indexes for all ctin headers
for (let i = 0; i < ctinIndexes.length; i++) {
[0,1].forEach(rowIndex => {
const sliced = array[rowIndex].slice(ctinIndexes[i], ctinIndexes[i + 1]); // Extract ctin segment
sliced.unshift("","",""); // Columns A to C should be empty
array.push(sliced); // Add each ctin segment to the 2D array
});
}
[0,1].forEach(rowIndex => array[rowIndex].splice(ctinIndexes[0])); // Remove other ctin data from first two rows
const sheet = SpreadsheetApp.getActive().getSheetByName("Copy of Data");
for (let i = 0; i < array.length; i = i + 2) {
sheet.getRange(sheet.getLastRow() + 1, 1, 2, array[i].length).setValues(array.slice(i, i + 2));
} // Write array to sheet. Rows have different dimensions, so cannot be written all at once
}
In this case, the output is:
This should work for a specific json file. Since opening a JSON file in drive is a bit hard to get the file ID you can use the first function to get the ID.
EDIT:
When you run the first function you can look-up the jsonfile ID in the logs -> View -> Log. Then insert this ID in the second function under // Change file id
//With this function you can get the ID of you json file. After running see the view -> Logs for the info.
function getDriveFileID() {
//Change id of the drive folder found in the url
const folderID = "1UN3xxxpE8mXjHHJJF";
const driveFolder = DriveApp.getFolderById(folderID);
const driveFiles = driveFolder.getFiles();
while(driveFiles.hasNext()){
let file = driveFiles.next();
console.log(file.getName()," = ",file.getId());
};
}
function JSON_from_DRIVE() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
//change output sheetname
const sheet = ss.getSheetByName("Data");
//Change file id
const file = DriveApp.getFileById("1IPyU2nxxxxx_lr0F").getBlob().getDataAsString();
const dataAll = JSON.parse(file);
const dataRows = dataAll['b2b'];
const rowHeaders = Object.keys(dataRows[0]);
const rows = [rowHeaders];
for (var i = 0; i < dataRows.length; i++) {
var rowData = [];
for (var j = 0; j < rowHeaders.length; j++) {
rowData.push(dataRows[i][rowHeaders[j]]);
}
rows.push(rowData);
}
sheet.getRange(1,1,rows.length,rows[0].length).setValues(rows);
}
EDIT: this should work custom for your json file.
//With this function you can get the ID of you json file. After running see the view -> Logs for the info.
function getDriveFileID() {
//Change id of the drive folder found in the url
const folderID = "1UN3xxxpE8mXjHHJJF";
const driveFolder = DriveApp.getFolderById(folderID);
const driveFiles = driveFolder.getFiles();
while (driveFiles.hasNext()) {
let file = driveFiles.next();
console.log(file.getName(), " = ", file.getId());
};
}
function JSON_from_DRIVE() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
//change output sheetname
const sheet = ss.getSheetByName("Data");
//Change file id
const file = DriveApp.getFileById("1IPyU2nxxxxx_lr0F").getBlob().getDataAsString();
const dataAll = JSON.parse(file);
const b2b = dataAll['b2b'];
const dataRows = [];
b2b.forEach(base => {
base.inv.forEach(inv => {
const obj = {
"ctin": base.ctin,
"cfs": base.cfs,
"cfs3b": base.cfs3b,
"val": inv.val,
"num": inv.itms[0].itm_det.csamt,
"csamt": inv.itms[0].itm_det.csamt,
"samt": inv.itms[0].itm_det.samt,
"rt": inv.itms[0].itm_det.rt,
"txval": inv.itms[0].itm_det.txval,
"camt": inv.itms[0].itm_det.camt,
"inv_type": inv.inv_typ,
"pos": inv.pos,
"idt": inv.idt,
"rchrg": inv.rchrg,
"inum": inv.inum,
"chksum": inv.chksum,
"fldtr1": base.fldtr1,
"flprdr1": base.flprdr1
}
newObj.push(obj);
});
});
const rowHeaders = Object.keys(dataRows[0]);
const rows = [rowHeaders];
for (var i = 0; i < dataRows.length; i++) {
var rowData = [];
for (var j = 0; j < rowHeaders.length; j++) {
rowData.push(dataRows[i][rowHeaders[j]]);
}
rows.push(rowData);
}
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}

GULP Create JSON file from another JSON file

I am trying to create a local lang file that will be formatted as json. I have the following navigation in json format below. And I need to create a new JSON file using GULP to create a lang file (see below)
"lists": [
{
"title": "Application Intel",
"items": [
{
"title": "Analytics Dashboard",
"href": "intel_analytics_dashboard.html"
},
{
"title": "Marketing Dashboard",
"href": "intel_marketing_dashboard.html"
},
{
"title": "CEO Dashboard",
"href": "intel_ceo_dashboard.html"
},
{
"title": "Introduction",
"href": "intel_introduction.html"
},
{
"title": "Build Notes",
"href": "intel_build_notes.html",
"text": "Build Notes",
"span": {
"class": "",
"text": "v{{version}}"
}
}
]
}
I need to create a file that looks like the following json:
"nav": {
"application_intel": "Application Intel",
"intel_analytics_dashboard": "Analytics Dashboard",
"intel_marketing_dashboard": "Marketing Dashboard",
"intel_ceo_dashboard": "CEO Dashboard",
"intel_introduction": "Introduction",
"intel_build_notes": "Build Notes",
}
Whats the best way to go about this?
Here is solution.
Let's say you have nav.json file inside src and you want to change its shape and place it into dest directory. You can achieve this from within gulpfile.js
const { src, dest } = require("gulp");
const through = require("through2");
// gulp task
function json() {
return src("src/nav.json")
.pipe(
through.obj((file, enc, cb) => {
// get content of json file
const rawJSON = file.contents.toString();
// parse raw json into javscript object
const parsed = JSON.parse(rawJSON);
// transform json into desired shape
const transformed = transformJson(parsed);
// make string from javascript obj
const stringified = JSON.stringify(transformed, null, 2);
// make bufer from string and attach it as current file content
file.contents = Buffer.from(stringified);
// pass transformed file into next gulp pipe
cb(null, file);
})
)
.pipe(dest("dest"));
}
// transformation
function transformJson(input) {
const result = { nav: {} };
// read json field by field
Object.keys(input).forEach(topLevelKey => {
// current object
const topLevelItem = input[topLevelKey];
// in your design topLevelItems are arrays
topLevelItem.forEach(menuItem => {
if (menuItem.title) {
// make url either from item href or title
const itemUrl = makeUrl(menuItem.href || menuItem.title);
result.nav[itemUrl] = menuItem.title;
}
// prcoess children
if (menuItem.items) {
menuItem.items
.filter(child => !!child.title) // process only child items with title
.forEach(child => {
const childUrl = makeUrl(child.href || child.title);
result.nav[childUrl] = child.title;
});
}
});
});
return result;
}
// helper func
function makeUrl(href) {
return href
.toLowerCase()
.replace(/\.html$/, "")
.replace(/\s/g, "_");
}
// export for use in command line
exports.json = json;
json transformation function is bit forEachy and if you have deep nested navigation structure, maybe you should change it into something recursive

How can i get an array of images from a collection of nested objects with Lodash?

{
"shop": {
"homebackground": "http://padmenu.s3.amazonaws.com/15/11/2014/05/08/2ec2ff61-d6a0-11e3-8857-10ddb1e6e201.jpg",
"name": {
"tr": "My Shop"
},
"menus": [{
"name": {
"en": "Menu"
},
"children": [{
"name": {
"en_US": "Category"
},
"images": [
"http://www.progressivedental-ellenlimdds.com/wp-content/uploads/2014/06/red-wine.jpg"
],
"children": [{
"name": {
"en_US": "Item"
},
"images": [
"http://res.cloudinary.com/finedine/image/upload/c_fill,g_center,h_600/v1435916818/WIne-Bottle_uz03a0.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3",
"http://lorempixel.com/400/400/food/4",
"http://lorempixel.com/400/400/food/5",
"http://lorempixel.com/400/400/food/6",
"http://lorempixel.com/400/400/food/7"
]
}]
}]
}]
}
}
I want to select all the "images" arrays from shop's "children" objects.
How can i do this by using Lodash library?
The output should be an array of consists of image urls:
["url1","url2","url3"]
The easiest approach to solve this problem is by plucking through children and their descendants recursively. The important points are in the getImages() function; wherein it flattens all children arrays in one level, pluck each image arrays and compact all items to remove undefined values(caused by children with no images), and then flattening the images array and readied for concatenation. The stopping point of the recursion is when there are no images for the current children, returning an empty array. If images are found, then we recursively concatenate all potential descendant images. As to how we get the descendants, we use the same chaining sequence that we used in getting the images array but with children as the plucking key.
DEMO
function getImages(children) {
var images = _(children).flatten().pluck('images').compact().flatten().value();
if(_.isEmpty(images)) {
return [];
}
var descendants = _(children).flatten().pluck('children').compact().flatten().value();
return images.concat(getImages(descendants));
}
function getShopImages(data) {
var children = _.pluck(data.shop.menus, 'children');
return getImages(children);
}
console.log(getShopImages(data));
Pseudo Code
You can solve this with a little bit of recursion:
Grab the children list.
Extract all the images from the children list with pluck.
Repeat step 1 with all descendants.
Concat all results and flatten.
Core Code
function deepExtract(collection, childKey, property) {
var exists = _.negate(_.isEmpty);
var children = _.chain(collection).pluck(childKey).filter(exists).flatten();
if (_.isEmpty(children.value())) {
return [];
}
var images = children.pluck(property).value();
var descendantImages = deepExtract(children.value(), childKey, property);
return _.flatten(images.concat(descendantImages));
};
var tree = _.chain(data).get('shop.menus').value();
var images = deepExtract(tree, 'children', 'images');
Demo
var data = {
"shop": {
"homebackground": "http://padmenu.s3.amazonaws.com/15/11/2014/05/08/2ec2ff61-d6a0-11e3-8857-10ddb1e6e201.jpg",
"name": {
"tr": "My Shop"
},
"menus": [{
"name": {
"en": "Menu"
},
"children": [{
"name": {
"en_US": "Category"
},
"images": [
"http://www.progressivedental-ellenlimdds.com/wp-content/uploads/2014/06/red-wine.jpg"
],
"children": [{
"name": {
"en_US": "Item"
},
"images": [
"http://res.cloudinary.com/finedine/image/upload/c_fill,g_center,h_600/v1435916818/WIne-Bottle_uz03a0.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3",
"http://lorempixel.com/400/400/food/4",
"http://lorempixel.com/400/400/food/5",
"http://lorempixel.com/400/400/food/6",
"http://lorempixel.com/400/400/food/7"
]
}]
}]
}]
}
};
function deepExtract(collection, childKey, property) {
var exists = _.negate(_.isEmpty);
var children = _.chain(collection).pluck(childKey).filter(exists).flatten();
if (_.isEmpty(children.value())) {
return [];
}
var images = children.pluck(property).value();
var descendantImages = deepExtract(children.value(), childKey, property);
return _.flatten(images.concat(descendantImages));
};
var tree = _.chain(data).get('shop.menus').value();
log(deepExtract(tree, 'children', 'images'));
// Helper method to output to screen
function log(value) {
document.getElementById("output").innerHTML += JSON.stringify(value, null, 2) + "\n"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<pre id="output"></pre>
I found an alternative solution to my question here:
var children = _(shop.menus[0].children)
.thru(function(coll) {
return _.union(coll, _.pluck(coll, 'children'));
})
.flatten();
var images = _.chain(children).pluck('images').flattenDeep().compact().uniq().value();
The output "images" is an image array.

Json response + Node.js

In my node app i pass bunch of queries as Object.I have to form as exact format of request.
Consider my request as:
{q0:{query0},q1:{query1},q2:{query1}}
My reponse should be {q0:{response0},q1{response1},q2{response2}
My actual query(In my app):
{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"},
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"},
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"},
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"},
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}}
But my response is coming as:
{"result":[q0result,q1result,q3result]}
My code:
for (var id in presidents ) {
var match
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches.push({
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
})
}
callback(matches);
json = JSON.stringify({"result":matches});
res.writeHead(200, {'content-type':'application/json'});
res.end(json);
Please help me to solve this..Thanks in advance.
You are pushing the result in an array instead you should create a property in the result object as below
var matches = {};
for (var id in presidents ) {
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches[id] ={
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
};
}
callback(matches);

Using QUERY URL to group data before sending to Google Apps Script dashboard

I have a Google Spreadsheet, with say a key 'ABCKEY' and would like to perform the QUERY (SQL) function on the data before using the data in a Google Apps Script dashboard.
var ss = SpreadsheetApp.openById('ABCKEY');
var mydata = ss.getDataRange();
This article explains how one can use the QUERY feature on the data in the spreadsheet to produce grouped data.
The following query produces the correct grouped data I would like to use as the data source of my Google Apps Script dashboard:
https://spreadsheets.google.com/a/mybusinessappdomain.com/tq?key=ABCKEY&tq=select%20A%2CC%2Csum(F)%2Csum(G)%20group%20by%20A%2C%20C
I would therefore essentially like to populate the mydata variable above with the result from the above SQL query, which produces a JSON output string.
How can this be accomplished?
The approach I propose is this:
Use UrlFetchApp.fetch() to get the results of the query uri into a variable in your script. The query URI returns javascript to set results for the google visualization service.
Remove any extraneous content in the result, leaving only the JSON representation of the query results. A simple regex extraction can do this, and then we can parse the extracted string into a JSON object.
Decode the JSON object into a two-dimensional array, mydata. This requires some understanding of how the table is represented as a JSON object in the visualization query.
The JSON query result is structured like this:
{
"version": "0.6",
"status": "ok",
"sig": "862651648",
"table": {
"cols": [
{
"id": "A",
"label": "",
"type": "string",
"pattern": ""
},
{
"id": "D",
"label": "Population Density",
"type": "number",
"pattern": "#0.###############"
}
],
"rows": [
{
"c": [
{
"v": "Indonesia"
},
{
"v": 117,
"f": "117"
}
]
},
{
"c": [
{
"v": "China"
},
{
"v": 137,
"f": "137"
}
]
},
{
"c": [
{
"v": "Nigeria"
},
{
"v": 142,
"f": "142"
}
]
},
{
"c": [
{
"v": "Pakistan"
},
{
"v": 198,
"f": "198"
}
]
},
{
"c": [
{
"v": "India"
},
{
"v": 336,
"f": "336"
}
]
},
{
"c": [
{
"v": "Japan"
},
{
"v": 339,
"f": "339"
}
]
},
{
"c": [
{
"v": "Bangladesh"
},
{
"v": 1045,
"f": "1045"
}
]
}
]
}
}
You'll notice that the table object consists of an array of cols objects that describe the columns in the table. For your array, the portion that you're interested in is the label for the column.
After that, the table object contains an array of rows objects, each with an array of c objects with the data for each column in the row. For your array, it's the v or value that you're interested in. (f contains a formatted version of the same data)
So our parser will iterate through the column headers first, then through each row of the table, pushing the values-of-interest into a two-dimensional array, mydata.
For this example, I'm accessing the public spreadsheet used in the Interactive Code Sample provided in the Query Language Reference, and also using their sample query. I've written the example so it can be easily modified to access your own spreadsheet with your own query. Here's the code:
// Specify the spreadsheet key and the query to be retrieved
var ssKey = 'pCQbetd-CptGXxxQIG7VFIQ';
var query = encodeURIComponent('SELECT A,D WHERE D > 100 ORDER BY D');
// Build url to peform query
var url = 'http://spreadsheets.google.com/tq?key=%KEY%&tq=%QUERY%'
.replace('%KEY%',ssKey)
.replace('%QUERY%',query);
// Use UrlFetchApp to get the results of the query as a string.
var response = UrlFetchApp.fetch(url);
var content = response.getContentText();
//Logger.log(content);
// Extract the JSON object from the response. Note that the response contains
// multiple lines of Javascript, and that it's the second line that has our
// data table in it.
var regex = /.*google.visualization.Query.setResponse\((.*)\)/g
var jsonContent = regex.exec(content)[1];
Logger.log(jsonContent);
var objectContent = Utilities.jsonParse(jsonContent);
var numCols = objectContent.table.cols.length;
var numRows = objectContent.table.rows.length;
// Decode objectContent into a two-dimensional array.
var mydata = []
// Start with the header row.
mydata[0] = [];
for (var col = 0; col < numCols; col++ ) {
mydata[0].push(objectContent.table.cols[col].label);
}
// Then data rows
for (var row = 0; row < numRows; row++) {
mydata[row+1] = [];
for (var col = 0; col < numCols; col++ ) {
mydata[row+1].push(objectContent.table.rows[row].c[col].v);
}
}
// Done - mydata is now a two-dimensional array with the results of the query
debugger; // If debugging, pause to examine results
Depending on what you're planning to use the data for in your dashboard, you may just want to use the table object after the call to jsonParse().
I do not think the json parser var objectContent = Utilities.jsonParse(jsonContent) would work with those visualization query response having date as one of the cell value such as the below example
{
"v": newDate(2013,
11,
31),
"f": "31-Dec-2013",
"p": {
"style": "color: rgb(0, 0, 0);font-family:Dialog;"
}
}