I have 1 entry in my local storage file
10/10/2014 19:23:34 (date and time) as a key and
{"entries":[{"name":"s","contact":"s","location":"s","email":"sweety#yahoo.com","detail":"s","f_name":"form1"}]}
(form field records) as value
so my question is how to get this array with separated parameters like Name = s, Contact = s, etc...
If you didn't already parse your data you can parse it like this:
var json = localStorage.getItem('10/10/2014 19:23:34');
if (json) {
var data = JSON.parse(json);
if (data !== null) {
// then you can try to do something with the data within it
var entries = data.entries;
for (var i = 0, l = entries.length; i < l; i++) {
var entry = entries[i];
console.log(entry.name, entry.contact, entry.location, entry.email);
}
}
}
Related
----- BACKGROUND ----- In Google Sheets/Apps Script, I'm trying to move some transaction data from one sheet and organize it on a different sheet with subtotal rows for each customer account (called "Units") with a grand total at the bottom.
I have the transactions organized in an array of objects as key:value pairs ("transactions", the keys are headers, some values are strings, others are numbers), and I have the units in a 2nd array called "unitList". I want to iterate through each element in the unitList array, and pull each transaction with a matching unit onto my "targetSheet", then append a subtotal row for each unit.
----- UPDATE 10/7/2018 3:49PM EST -----
Thanks to everyone for your input - I took your advice and ditched the library I was using and instead found better getRowsData and appendRowsData functions which I put directly in my code project. This fixed the array filter problem (verified by logging filterResults), BUT, now when I call appendRowsData(), I get this error:
The coordinates or dimensions of the range are invalid. (line 73, file "Display Transactions")
Line 73 is the line below, in the appendRowsData function. Any help on how to fix this would be greatly appreciated.
var destinationRange = sheet.getRange(firstDataRowIndex, 1, objects.length, 9);
Here's my project in it's entirety thus far:
function displayTransactions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Label each sheet
var dashboard = ss.getSheetByName('Dashboard');
var unitsSheet = ss.getSheetByName('Unit Ref Table');
var transactionsSheet = ss.getSheetByName('Transactions Ref Sheet');
var targetSheet = ss.getSheetByName('Target Sheet');
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Define function that converts arrays into JSON
// For every row of data in data, generates an object that contains the data.
// Names of object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Define function that pulls spreadsheet data into arrays, then converts to JSON using getObjects function
function getRowsData(sheet) {
var headersRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var headers = headersRange.getValues()[0];
var dataRange = sheet.getRange(sheet.getFrozenRows()+1, 1, sheet.getLastRow(), sheet.getLastColumn());
return getObjects(dataRange.getValues(), headers);
}
// Define function appendRowsData that uses getLastRow to fill in one row of data per object defined in the objects array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the sheet object where the data will be written
// - objects: an array of objects, each of which contains data for a row
function appendRowsData(sheet, objects) {
var headersRange = sheet.getRange(7, 1, 1, 9);
var firstDataRowIndex = sheet.getLastRow() + 1;
var headers = headersRange.getValues()[0];
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
var destinationRange = sheet.getRange(firstDataRowIndex, 1, objects.length, 9);
destinationRange.setValues(data);
}
// Call getRowsData on transactions sheet
var transactions = getRowsData(transactionsSheet);
// Get array of units
var unitList = unitsSheet.getRange("B2:B").getValues();
// Iterate through the unitList and pull all transactions with matching unit into the target sheet
for (var i=0; i < unitList.length; i++) {
var subTotal = 0;
var grandTotal = 0;
var filterResults = transactions.filter(function(x) {
return x['Unit'] == unitList[i];
})
Logger.log(filterResults); // This brings the correct results!
// Display matching transactions
appendRowsData(targetSheet, filterResults);
// Grand total at the bottom when i=units.length
}
}
I having an google app (app maker) where I script the following code:
function runQuery() {
var projectId = 'projekte-123425512';
var request = {
query: 'SELECT title FROM [bigquery-public-data:samples.wikipedia] where title contains "olimpic" LIMIT 100'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var names = queryResults.schema.fields.map(function(field){ return field.name; });
return queryResults.rows.map(function(row) {
var obj = {};
for( var i = 0, len = names.length; i < len; ++i ) {
obj[names[i]] = row.f[i].v;
}
return obj;
});
}
So I basically try to get some data out of Big Query and store it in an array. Later I want it as a calculated model and a data source in my app:
I already tried it and get result in my logger:
It works! But only in app script debugger, then I want to test the whole app I get the following error:
The function queryRecords must return an array of records, but the array contained an element that was not a record. Error: The function queryRecords must return an array of records, but the array contained an element that was not a record.
EDIT
I updated my code
function runQuery() {
var projectId = 'nifty-stage-155512';
var request = {
query: 'SELECT title FROM [bigquery-public-data:samples.wikipedia] where title contains "olimpic" LIMIT 100'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var names = queryResults.schema.fields.map(function(field){ return field.name; });
//var records = [];
return queryResults.rows.map(function(row) {
var record = app.models.Test.newRecord();
for (var i = 0, len = names.length; i < len; ++i) {
// Calculated model should contain correspondent fields
// all non-defined fields will be ignored
record[names[i]] = (row.f[i].v);
}
return record;
});
}
It now works without error but I still get no data into my grid:
Is there something I'am missing in the configuration of the grid or the datasource??
App Maker doesn't allow to return arbitrary objects through its datasources. All results should be strongly typed:
...
return queryResults.rows.map(function(row) {
var record = app.models.CalcModelName.newRecord();
for (var i = 0, len = names.length; i < len; ++i) {
// Calculated model should contain correspondent fields
// all non-defined fields will be ignored
record[names[i]] = row.f[i].v;
}
return record;
});
Here are some samples for reference
https://developers.google.com/appmaker/samples/calculated-model/
https://developers.google.com/appmaker/samples/jdbc/
I'm trying to fetch my ETH balance and transactions from etherscan.io website and I'm trying to use the same code I used before for another website. But it seems returning me an empty array, and also the error "The coordinates or dimensions of the range are invalid."
This is the code:
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.length; i++) {
array = data[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 3);
askRange.setValues(rows);
}
The logged "rows" is empty, what am I doing wrong?
Thank you
How about a following modification?
Modification points :
There is data you want at data.result.
Number of columns of data is 4.
Modified script :
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.result.length; i++) { // Modified
array = data.result[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 4); // Modified
askRange.setValues(rows);
}
If I misunderstand your question, I'm sorry.
I have response from database:
{"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188},
...
{"id":1170,"sku":0,"word_one":"something","description":"","word_two":"some two","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"ever\"},{\"text\":\"never\"}]","UserID":188}]}
Before I make post: angular.toJson($scope.category);
How I can show category something like this
{{category}} = someone, sometwo ?
Because actually I have string :
[{"text":"someone"},{"text":"sometwo"}]
[{"text":"ever"},{"text":"never"}]
...
You can use the below parsing to achieve what you want. Suppose json is the variable received from database.
var json = {"status":"success","message":"Data selected from database","data":[{"id":1171,"sku":0,"word_one":"one word","description":"","word_two":"two word","mrp":0,"lang_one":"en","image":"","lang_two":"en","status":"Active","category":"[{\"text\":\"someone\"},{\"text\":\"sometwo\"}]","UserID":188}]};
var data = json.data[0].category;
var jsonArray = JSON.parse(data);
var category = "";
jsonArray.map(function(obj, i ) {
if(i != 0) {
category += ",";
}
category += obj.text;
});
console.log(category)
At the end , You attach category to $scope.category.
This work:
var parsed = JSON.parse($scope.c.category);
var arr = [];
for(var x in parsed){
arr.push(parsed[x]);
}
$scope.c.category = arr;
How can i split and parse particular json data using angularjs.
My json is
[{"id":"1", "stud":" name=Alex, roll_no=12 | class=12,sec=1" , "tech":"Sam"},
{"id":"2", "stud":" name=john, roll_no=13 | class=12,sec=2" , "tech":"Sandy"},
{"id":"3", "stud":" name=Cate, roll_no=14 | class=12,sec=1" , "tech":"Sandy"},
]
I want to parse this json formated data like if ID =1 .
Name= Alex.
Roll No=12.
Class=12.
Section=1.
Teacher=Sam.
Iterate through the collection with reduce.
On every Object in the collection parse the stud attribute with Regular Expressions. Create the new string and add it to the new collection.
// Pseudocode
collection.reduce((memo, item) => {
const values = item.stud.match(" name=Alex, roll_no=12 | class=12,sec=1".match(/^ name=(\w*), roll_no=(\d{2}).../))
// Add it to memo in a format you like
return memo
})
I wrote you some functions...
function getRowFromJson(json, id){
for(var i=0; i<json.length; i++)
if('undefined' == json[i].id) continue;
else if(json[i].id==id) return json[i];
return false;
}
function parseStudFromRow(row){
var stud = {};
var chunks = row.stud.split("|");
for(var i=0; i<chunks.length; i++){
var morechunks = chunks[i].split(",");
for(var n=0; n<morechunks.length; n++){
var chunkage = morechunks[n].split("=");
stud[chunkage[0].trim()] = chunkage[1].trim();
}
}
return stud;
}
You use it like this..
var row = getRowFromJson(json, 1);
var stud = parseStudFromRow(row);
console.log(stud);
Check out the example.. https://jsfiddle.net/o0v6nyzu/2/