Pagination for Google Apps Script with Shopify API - api

I am running into a bit of a snag setting up pagination in Google Apps Script. I am trying to use it for Shopify API. Reference links attached.
I attached the code below of what I have so far -
trying to figure out how to use the "While" statement to make it check if there is a Next Page URL
trying to figure out a way to parse the Link in the header. Example below. On pages 2+ there will be a next and previous link. We only need the next
https://shop-domain.myshopify.com/admin/api/2019-07/products.json?limit=50&page_info=eyJkaXJlY3Rpb24iOiJwcmV2IiwibGFzdF9pZCI6MTk4NTgyMTYzNCwibGFzdF92YWx1ZSI6IkFjcm9saXRoaWMgQWx1bWludW0gUGVuY2lsIn0%3D; rel="previous", https://shop-domain.myshopify.com/admin/api/2019-07/products.json?limit=50&page_info=eyJkaXJlY3Rpb24iOiJuZXh0IiwibGFzdF9pZCI6MTk4NTgzNjU0NiwibGFzdF92YWx1ZSI6IkFoaXN0b3JpY2FsIFZpbnlsIEtleWJvYXJkIn0%3D; rel="next
function callShopifyOrderCount() {
var accessToken = 'xxxx';
var store_url = 'https://xxxx.myshopify.com/admin/api/2021-01/orders.json?status=any&fields=created_at,id,name,total-price&limit=20';
var headers = {
"Content-Type": "application/json",
'X-Shopify-Access-Token': accessToken
};
var options = {
"method": "GET",
"headers": headers,
"contentType": "application/json",
"muteHttpExceptions": true,
}
var response = UrlFetchApp.fetch(store_url, options)
// Call the link header for next page
var header = response.getHeaders()
var linkHeader = header.Link;
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody);
var objectLength = responseJson.orders.length;
for (var i = 0; i < objectLength; i++) {
var orderId = responseJson.orders[i].id;
var orderPrice = responseJson.orders[i].total_price;
var orderName = responseJson.orders[i].name;
}
} else {
Logger.log(
Utilities.formatString(
"First Request failed. Expected 200, got %d: %s",
responseCode,
responseBody
)
);
// ...
}
// *** NEED TO FIGURE OUT WHILE STATEMENT //
while (Link != null) {
var store_url = linkHeader;
var response = UrlFetchApp.fetch(store_url, options)
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
var header = response.getHeaders()
var linkHeader = header.Link;
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody);
var objectLength = responseJson.orders.length;
for (var i = 0; i < tweetLength; i++) {
var orderId = responseJson.orders[i].id;
var orderPrice = responseJson.orders[i].total_price;
var orderName = responseJson.orders[i].name;
}
}
else {
Logger.log(
Utilities.formatString(
"Second Request failed. Expected 200, got %d: %s",
responseCode,
responseBody
)
);
}
}
}
References:
https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api
https://www.shopify.com/partners/blog/relative-pagination

Related

Limiting Loop Range to 100 Rows at at time

I have the following script that takes data from my Sheet and updates records via a POST API call; however there is a limit of 100 calls at a time so I'm looking for a way to add that to my script if possible. I also need to ensure that the header row (row1) is sent. So essentially the first loop is rows 1-101, second loop is row 1 and rows 102-201 etc. Not even sure this is possible
function updateManyUsers() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var [headers, ...rows] = sheet.getDataRange().getDisplayValues();
Logger.log([headers,rows]);
var users = rows.map(r => {
var temp = {};
headers.forEach((h, j) => {
if (r[j] != "") temp[h] = r[j];
});
return temp;
});
var url = 'https://redaccted.zendesk.com/api/v2/users/update_many.json';
var user = 'morris.coyle#redacted_still/token';
var pwd = 'Every_redacted';
var options = {
'method': 'PUT',
'headers': {
'Authorization': "Basic " + Utilities.base64Encode(user + ':' + pwd)
},
'payload': JSON.stringify({ users }),
'contentType': 'application/json',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
Thanks in advance.
Moz
Description
I have created a simple example of how to slice 100 rows from the data.
I have a simple data set of Header plut 256 rows of data. See screen shot.
Screen shots
Script
function updateManyUsers() {
try {
let spread = SpreadsheetApp.getActiveSpreadsheet();
let sheet = spread.getSheetByName("Sheet1");
let values = sheet.getDataRange().getValues();
console.log("rows = "+values.length);
let headers = values.shift();
let i = 0;
let numUsers = 100;
let j = numUsers;
while( i < values.length ) {
if( j < values.length ) {
var users = [].concat(headers,values.slice(i,j));
}
else {
var users = [].concat(headers,values.slice(i));
}
console.log("header = "+users[0][0]);
console.log("users[1] = "+users[1][0]);
console.log("users[99] = "+users[users.length-1][0]);
i = i+numUsers;
j = j+numUsers;
// Now build your opsions
}
}
catch(err) {
console.log(err);
}
}
1:18:04 PM Notice Execution started
1:18:05 PM Info rows = 257
1:18:05 PM Info header = Header
1:18:05 PM Info users[1] = 1
1:18:05 PM Info users[99] = 100
1:18:05 PM Info header = Header
1:18:05 PM Info users[1] = 101
1:18:05 PM Info users[99] = 200
1:18:05 PM Info header = Header
1:18:05 PM Info users[1] = 201
1:18:05 PM Info users[99] = 256
1:18:05 PM Notice Execution completed
Reference
Array.shift()
Array.concat()
Array.slice()
You can try this for-loop method that iterates every 100:
function updateManyUsers() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var data = sheet.getDataRange().getDisplayValues();
var headers = data.shift(); //remove headers to the array and assign it to headers variable
for (var i = 0; i < data.length; i += 100){
var tempArr = data.slice(i, i+100)
var users = tempArr.map(r => {
var temp = {};
headers.forEach((h, j) => {
if (r[j] != "") temp[h] = r[j];
});
return temp;
});
var url = 'https://redaccted.zendesk.com/api/v2/users/update_many.json';
var user = 'morris.coyle#redacted_still/token';
var pwd = 'Every_redacted';
var options = {
'method': 'PUT',
'headers': {
'Authorization': "Basic " + Utilities.base64Encode(user + ':' + pwd)
},
'payload': JSON.stringify({"users": users }),
'contentType': 'application/json',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
}
}
Sample data:
......
variable users content on each iteration:
Also, upon checking the documentation, when using Update Many Users batch update the data format should look like this:
{
"users": [
{ "id": 10071, "name": "New Name", "organization_id": 1 },
{ "id": 12307, "verified": true }
]
}
I'd propose to make three functions: main(), get_all_users(), update_users() and run the latter function in the loop this way:
function main() {
var all_users = get_all_users();
for (var i = 0; i < all_users.length; i += 100) {
var users = all_users.slice(i, i + 100);
update_users(users);
}
}
function get_all_users() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var [headers, ...rows] = sheet.getDataRange().getDisplayValues();
Logger.log([headers, rows]);
var users = rows.map((r) => {
var temp = {};
headers.forEach((h, j) => { if (r[j] != "") temp[h] = r[j] });
return temp;
});
return users;
}
function update_users(users) {
var url = "https://redaccted.zendesk.com/api/v2/users/update_many.json";
var user = "morris.coyle#redacted_still/token";
var pwd = "Every_redacted";
var options = {
method: "PUT",
headers: {
Authorization: "Basic " + Utilities.base64Encode(user + ":" + pwd),
},
payload: JSON.stringify({ users }),
contentType: "application/json",
muteHttpExceptions: true,
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
}
It's always a good idea to keep the main function as short and clear as it's possible. And break the algo into the separate functions where every function does exactly one relatively simply thing: get users from the sheet, send request, etc.

Bings Ads Script - Calling Google Services not working

I'm trying to run a script in Bing Ads that will get the performance data and write it in Google Sheets. I based my code on Microsoft example: https://learn.microsoft.com/en-us/advertising/scripts/examples/calling-google-services
However, my code won't work.
function main() {
// Set these fields based on the option you chose for getting an access token.
const credentials = {
accessToken: '',
clientId: '',
clientSecret: '',
refreshToken: ''
};
 
// To get a fileId or spreadsheetId, please see
// https://developers.google.com/sheets/api/guides/concepts#spreadsheet_id.
 
// The file must contain a single bid multiplier value (for example,1.1),
// which is used to update keyword bids.
const fileId = 'INSERT FILE ID HERE';
 
// The spreadsheet must contain 3 valid keyword IDs in cells A2, A3, and A4.
const spreadsheetId = 'INSERT SPREADSHEET ID HERE';
// The email address to send a notification email to at the end of the script.
const notificationEmail = 'INSERT EMAIL HERE';
 
var driveApi = GoogleApis.createDriveService(credentials);
 
// Read bid multiplier from the file.
// Reference: https://developers.google.com/drive/api/v3/reference/files/export
var bidMultiplier = driveApi.files.export({ fileId: fileId, mimeType: 'text/csv' }).body;
 
Logger.log(`read bid multiplier ${bidMultiplier}`);
 
var sheetsApi = GoogleApis.createSheetsService(credentials);
 
// Write the old and new bid values back to the spreadsheet.
// Reference: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate
var campaignData = [];
var campaigns = AdsApp.campaigns().withCondition('Cost > 0').forDateRange('THIS_MONTH');
var campaignIterator = campaigns.get();
var iterator = 0;
while(campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
var campaignName = campaign.getName();
var stats = campaign.getStats();
var cost = stats.getCost();
var clicks = stats.getClicks();
var conversions = stats.getConversions();
   var impressions = stats.getImpressions();
campaignData[iterator] = {"CampaignName":campaignName,"cost":cost,"clicks":clicks,"conversions":conversions,"impressions":impressions};
iterator++;
}
var updateResponse = sheetsApi.spreadsheets.values.batchUpdate({ spreadsheetId: spreadsheetId }, {
data: [
{ range: 'A2:G2', values: campaignData.map(x => [x]) },
],
valueInputOption: 'USER_ENTERED'
});
 
Logger.log(`updated ${updateResponse.result.totalUpdatedCells} cells`);
 
var gmailApi = GoogleApis.createGmailService(credentials);
 
var email = [
`To: ${notificationEmail}`,
'Subject: Google Services script',
'',
`You script ran successfully ✓ and updated ${updateResponse.result.totalUpdatedCells} cells.`
].join('\n');
 
// Send the notification email.
// Reference: https://developers.google.com/gmail/api/v1/reference/users/messages/send
var sendResponse = gmailApi.users.messages.send({ userId: 'me' }, { raw: Base64.encode(email) });
 
Logger.log(`sent email thread ${sendResponse.result.threadId}`);
}
 
var GoogleApis;
(function (GoogleApis) {
function createSheetsService(credentials) {
return createService("https://sheets.googleapis.com/$discovery/rest?version=v4", credentials);
}
GoogleApis.createSheetsService = createSheetsService;
 
function createDriveService(credentials) {
return createService("https://www.googleapis.com/discovery/v1/apis/drive/v3/rest", credentials);
}
GoogleApis.createDriveService = createDriveService;
 
function createGmailService(credentials) {
return createService("https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest", credentials);
}
GoogleApis.createGmailService = createGmailService;
 
// Creation logic based on https://developers.google.com/discovery/v1/using#usage-simple
function createService(url, credentials) {
var content = UrlFetchApp.fetch(url).getContentText();
var discovery = JSON.parse(content);
var baseUrl = discovery['rootUrl'] + discovery['servicePath'];
var accessToken = getAccessToken(credentials);
var service = build(discovery, {}, baseUrl, accessToken);
return service;
}
 
function createNewMethod(method, baseUrl, accessToken) {
return (urlParams, body) => {
var urlPath = method.path;
var queryArguments = [];
for (var name in urlParams) {
var paramConfg = method.parameters[name];
if (!paramConfg) {
throw `Unexpected url parameter ${name}`;
}
switch (paramConfg.location) {
case 'path':
urlPath = urlPath.replace('{' + name + '}', urlParams[name]);
break;
case 'query':
queryArguments.push(`${name}=${urlParams[name]}`);
break;
default:
throw `Unknown location ${paramConfg.location} for url parameter ${name}`;
}
}
var url = baseUrl + urlPath;
if (queryArguments.length > 0) {
url += '?' + queryArguments.join('&');
}
var httpResponse = UrlFetchApp.fetch(url, { contentType: 'application/json', method: method.httpMethod, payload: JSON.stringify(body), headers: { Authorization: `Bearer ${accessToken}` }, muteHttpExceptions: true });
var responseContent = httpResponse.getContentText();
var responseCode = httpResponse.getResponseCode();
var parsedResult;
try {
parsedResult = JSON.parse(responseContent);
} catch (e) {
parsedResult = false;
}
var response = new Response(parsedResult, responseContent, responseCode);
if (responseCode >= 200 && responseCode <= 299) {
return response;
}
throw response;
}
}
 
function Response(result, body, status) {
this.result = result;
this.body = body;
this.status = status;
}
Response.prototype.toString = function () {
return this.body;
}
 
function build(discovery, collection, baseUrl, accessToken) {
for (var name in discovery.resources) {
var resource = discovery.resources[name];
collection[name] = build(resource, {}, baseUrl, accessToken);
}
for (var name in discovery.methods) {
var method = discovery.methods[name];
collection[name] = createNewMethod(method, baseUrl, accessToken);
}
return collection;
}
 
function getAccessToken(credentials) {
if (credentials.accessToken) {
return credentials.accessToken;
}
var tokenResponse = UrlFetchApp.fetch('https://www.googleapis.com/oauth2/v4/token', { method: 'post', contentType: 'application/x-www-form-urlencoded', muteHttpExceptions: true, payload: { client_id: credentials.clientId, client_secret: credentials.clientSecret, refresh_token: credentials.refreshToken, grant_type: 'refresh_token' } });
var responseCode = tokenResponse.getResponseCode();
var responseText = tokenResponse.getContentText();
if (responseCode >= 200 && responseCode <= 299) {
var accessToken = JSON.parse(responseText)['access_token'];
return accessToken;
}
throw responseText;
}
})(GoogleApis || (GoogleApis = {}));
 
// Base64 implementation from https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/master/lib/msal-core/src/Utils.ts
class Base64 {
static encode(input) {
const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let output = "";
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = this.utf8Encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return output.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
static utf8Encode(input) {
input = input.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < input.length; n++) {
var c = input.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
}
The first part of the code which brings back values from the spreadsheet works, but when it gets to writing the data in Google Sheets, I get an error and I don't know what it means.
{
"error": {
"code": 404,
"message": "Requested entity was not found.",
"status": "NOT_FOUND"
}
}
at (script code:142:7)

How can I get data from Bitfinex authenticated api endpoints using Google sheets?

Using Google sheets, I have stored my api_key and api_secret in the Property service section of user info as respectively "api_key" and api_secret".
I want to get wallet info from my account. The code I have written is as follows:
function wallet() {
var api_key = PropertiesService.getScriptProperties().getProperty('api_key');
var api_secret = PropertiesService.getScriptProperties().getProperty('api_secret');
var response = UrlFetchApp.fetch("https://api.bitfinex.com/v2/auth/r/wallets", api_key, api_secret);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet");
var result = JSON.parse(response.getContentText());
var wallet_btc = result.BALANCE
}
When I run in debug mode the error message is:
Cannot find method fetch(string,null,null). (line 13, file "Code")
Is this approach wrong, the code wrong, or both?
Many thanks.
How about the following modifications?
Modification points :
The parameters for UrlFetchApp.fetch() are UrlFetchApp.fetch(url, params). And params is an object.
This is the reason of error Cannot find method fetch(string,null,null). (line 13, file "Code").
When I saw the sample scripts for Bitfinex API, the request body has to be created using api_key, api_secret, nonce, body and signature. And signature is encrypted by HMAC_SHA_384 and converted to the string of the unsigned hexadecimal.
The sample for the endpoint of https://api.bitfinex.com/v2/auth/r/wallets is as follows. This is from API reference.
Sample for the endpoint of https://api.bitfinex.com/v2/auth/r/wallets
request.post(
`${url}/auth/r/wallets`,
headers: { /* auth headers */ },
body: {},
json: true,
(error, response, body) => console.log(body)
)
When above points are reflected to your script, the modified script is as follows.
Modified script :
function wallet() {
var api_key = PropertiesService.getScriptProperties().getProperty('api_key');
var api_secret = PropertiesService.getScriptProperties().getProperty('api_secret');
var apiPath = "v2/auth/r/wallets";
var nonce = Date.now().toString();
var body = {};
var rawBody = JSON.stringify(body);
var signature = "/api/" + apiPath + nonce + rawBody;
signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, signature, api_secret)
.map(function(e) {
var v = (e < 0 ? e + 256 : e).toString(16);
return v.length == 1 ? "0" + v : v;
}).join("");
var url = "https://api.bitfinex.com/" + apiPath;
var options = {
method: 'POST',
contentType: "application/json",
headers: {
'bfx-nonce': nonce,
'bfx-apikey': api_key,
'bfx-signature': signature
},
payload: rawBody
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
Logger.log(result)
// var wallet_btc = result.BALANCE // I couldn't confirm whether this key exists.
}
References :
Sample scripts for Bitfinex API
API reference
UrlFetchApp.fetch()
I cannot confirm whether this works. If this didn't work, can you tell me the situation? I would like to modify.
Edit :
When you want 0.0957596 from the result of [["exchange", "USD", 14.81076629, 0, null], ["exchange", "BTC", 0.0957596, 0, null], ["funding", "BTC", 4.13E-6, 0, null], ["funding", "ETH", 3.50186961, 0, null], ["exchange", "OMG", 5.9E-7, 0, null]];, you can use the following script.
Script :
function wallet() {
var api_key = PropertiesService.getScriptProperties().getProperty('api_key');
var api_secret = PropertiesService.getScriptProperties().getProperty('api_secret');
var apiPath = "v2/auth/r/wallets";
var nonce = Date.now().toString();
var body = {};
var rawBody = JSON.stringify(body);
var signature = "/api/" + apiPath + nonce + rawBody;
signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_384, signature, api_secret)
.map(function(e) {
var v = (e < 0 ? e + 256 : e).toString(16);
return v.length == 1 ? "0" + v : v;
}).join("");
var url = "https://api.bitfinex.com/" + apiPath;
var options = {
method: 'POST',
contentType: "application/json",
headers: {
'bfx-nonce': nonce,
'bfx-apikey': api_key,
'bfx-signature': signature
},
payload: rawBody
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
// Logger.log(result)
// var wallet_btc = result.BALANCE // I couldn't confirm whether this key exists.
var balance = 0;
for (var i in result) {
if (result[i][0] == "exchange" && result[i][1] == "BTC") {
balance = result[i][2];
break;
}
}
Logger.log(balance)
}
Note :
From the document, it seems that the indexes of WALLET_TYPE, CURRENCY and BALANCE are always 0, 1 and 2 of each element in the response, respectively.

Saving data from XMLHttpRequest Response to my IndexedDB

I have created a json file containing my Sql Server datas. With the XmlHttpRequest's GET method, I am reading json file and iterating and saving those records to my IndexedDB.. Everything is working fine.. After the end of the iteration, I wrote a code to alert the user.. But the alert message is displayed very quickly, but when I see it in the console window, the saving operation is till processing.. I want to alert the user, only after the operation is completed..
My code is,
if (window.XMLHttpRequest) {
var sFileText;
var sPath = "IDBFiles/Reservation.json";
//console.log(sPath);
var xhr = new XMLHttpRequest();
xhr.open("GET", sPath, 1);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != "") {
sFileText = xhr.responseText;
//console.log(sFileText);
var val = JSON.parse(sFileText);
var i = 0;
var value = val.length;
for(var i in val)
{
var code = val[i].RTM_res_category_code;
var desc = val[i].RTM_res_category_edesc;
addReserv(code, desc);
}
if(i >= value-1) {
console.log("Reservation Load Completed... "+i);
document.getElementById("status").innerHTML = "Reservation Loading Success...";
}
}
}
}
xhr.send();
}
//Passing Parameters to Reservation
function addReserv(code, desc)
{
document.querySelector("#status").innerHTML = "Loading Reservation.. Please wait...";
var trans = db.transaction(["Reservation"], "readwrite");
var store = trans.objectStore("Reservation");
//console.log(store);
var reserv={ RTM_res_category_code : code, RTM_res_category_edesc : ''+desc+'' };
var request = store.add(reserv);
request.onerror = function(e) {
console.log(e.target.error.name);
document.querySelector("#status").innerHTML = e.target.error.name;
}
request.onsuccess = function(e) {
console.log("Reservation Saved Successfully.");
//document.querySelector("#status").innerHTML = "Reservation Loaded Successfully.";
}
}
Thanks for the question.
What you are currently doing works, but the alert comes to soon because of the async nature of the IDB.
What you should to avoid this.
1. Create your transaction only once.
2. Do all your operations in this one transaction.
3. The transaction object has an oncomplete callback you can use to notify the user.
Concrete on your example. Instead of looping over the items in the ajax callback, pass the collection to your add method and loop there
if (window.XMLHttpRequest) {
var sFileText;
var sPath = "IDBFiles/Reservation.json";
//console.log(sPath);
var xhr = new XMLHttpRequest();
xhr.open("GET", sPath, 1);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText != "") {
sFileText = xhr.responseText;
//console.log(sFileText);
var val = JSON.parse(sFileText);
import(val);
}
}
}
xhr.send();
}
function import(values)
{
document.querySelector("#status").innerHTML = "Loading Reservation.. Please wait...";
var trans = db.transaction(["Reservation"], "readwrite");
var store = trans.objectStore("Reservation");
var i = 0;
var value = val.length;
for(var i in val)
{
var code = val[i].RTM_res_category_code;
var desc = val[i].RTM_res_category_edesc;
var reserv={ RTM_res_category_code : code, RTM_res_category_edesc : ''+desc+'' };
var request = store.add(reserv);
request.onerror = function(e) {
console.log(e.target.error.name);
document.querySelector("#status").innerHTML = e.target.error.name;
}
request.onsuccess = function(e) {
console.log("Reservation Saved Successfully.");
//document.querySelector("#status").innerHTML = "Reservation Loaded Successfully.";
}
}
trans.oncomplete = function () {
console.log("Reservation Load Completed... "+i);
document.getElementById("status").innerHTML = "Reservation Loading Success...";
}
}

How can i parse this JSON feed in Titanium Mobile App

How can i parse this JSON feed in Titanium Mobile App .
{
"data":{
"mat_78":{
"id":"78",
"title":"latest title here",
"teaser":"latest teaser here",
"body":"latest body here",
"logo":"http://sites/default/files/6_0.jpg",
"files":{
"323":{
"fid":"323",
"filename":"joudi1m.jpg",
"tumb":"http://sites/default/files/joudi1m_0.jpg",
"large":"http://sites/default/files/joudi1_0.JPG",
"caption":"joudi1m.jpg"
},
"471":{
"fid":"471",
"filename":"Shot-(0_00_15_09)m.jpg",
"tumb":"http://sites/default/files/Shot(0_00_15_09)m.jpg",
"large":"http://sites/default/files/Shot(0_00_15_09).jpg",
"caption":"Shot(0_00_15_09)m.jpg"
}
}
},
"mat_79":{
"id":"79",
"title":"latest title 2 here",
"teaser":"latest teaser 2 here",
"body":"latest body 2 here",
"logo":"http://sites/default/files/d09a0498a8512.jpg",
"files":{
"339":{
"fid":"339",
"filename":"BO1m.png",
"tumb":"http://sites/default/files/BO1_0.png",
"large":"http://sites/default/files/BO4_0.PNG",
"caption":"BO1m.png"
},
"340":{
"fid":"563",
"filename":"Slide9m.jpg",
"tumb":"http://sites/default/files/Slide9m.jpg",
"large":"http://sites/default/files/Slide9.JPG",
"caption":"Slide9m.jpg"
}
}
},
"mat_link":"mysite.cim/"
}
this is my code segment to parse the JSON . Bu its not getting .... its giving me 'undefined'
var loader = Titanium.Network.createHTTPClient();
loader.open("GET","http://mysite.com/data_iphone/en&lmt=5");
loader.onload = function()
{
var data = JSON.parse(this.responseData);
Ti.API.debug(data);
for (var i = 0; i < data.length; i++)
{
var my_id = data[i].id; // id
var my_title = data[i].title; // title
Ti.API.debug(my_title);
}
}
......
.........
I believe it should be more like this
// NOTICE EXTRA "data" on end, if you are using JSON.parse()
var data = JSON.parse(this.responseText).data;
Ti.API.debug(data);
for (var i = 0; i < data.length; i++)
{
var my_id = data[i].id; // id
var my_title = data[i].title; // title
Ti.API.debug(my_title);
}
use onload function for parse jason from yor server
var loader = Titanium.Network.createHTTPClient();
var requstUrl = "your url";
loader.open("GET", requstUrl);
loader.onload = function() {
var daysh = eval('(' + this.responseText + ')');
var status = daysh.status;
var jsonArry = daysh.locations;
for (var i = 0; i < jsonArry.length; i++)
{
alert(i);
}
};
loader.send();