Confused to read Json - json

I using titanium appcelerator..I had got a json to evaluate..I breaking my head to read the json values..
[[{"text":"hey"},{"text":"hey"},{"text":"hey"},{"text":"hey"},{"text":"hesssssssssy"},{"text":"hesssssssssy"},{"text":"hess"},{"text":"hessssy"},{"text":"hessssy"},{"text":"hesssssssssy"},{"text":"hesssssssssy"}],"13951406935634631","13951457282115774"]
How to read this one..
var e = JSON.stringify(res);
var response = eval("(" + e + ")");
Ti.API.info('..' + response[0]);
I'm in at first array.. But how should i get the length of response[0]

I got the solution..
This is how i solved..
for (var i = 0; i < response[0].length; i++) {
Ti.API.info(response[0][i].text);
}
Ti.API.info('length..' + response[0].length);
Ti.API.info('starttime..' + response[1]);
Ti.API.info('Endtime..' + response[2]);

Related

Execute Code as Fast as Possible

I am using node.js with my WebStorm IDE to parse a large JSON file (~500 megabytes). Here is my code:
fs = require("fs");
fs.readFile('C:/Users/.../Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 1000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var symbol = hex.substring(156, 179);
var timestamp = hex.substring(132, 155);
var askSize = hex.substring(240, 251);
var bidSize = hex.substring(180, 191);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
function hex2a(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
if(JSON.parse(data)[i]._source.layers.data["data.len"] == 84 && realprice.length == 8 && +realprice <154 && +realprice >145) {
console.log(i + " " + hex2a(symbol.replace(/:/g, "")) + " sold for " + realprice + " at " + parseInt(timestamp.split(":").reverse().join(""), 16));
}
}
});
The problem I am running into however is that my IDE is parsing this file at an extremely slow speed, roughly 1 iteration a second. I do not think this is because I have a slow computer, for I have a high end rig with a core i7 7700k and a gtx 1070. I tried executing the code in the console with the same result. I tried trimming down the code and again I achieved the same speed:
fs = require("fs");
fs.readFile('C:/Users/Brandt Winkler Prins/Documents/AAPL.json', 'utf8', function (err,data) {
for (i = 0; i < 12000; i++) {
var hex = JSON.parse(data)[i]._source.layers.data["data.data"];
var askPrice = parseInt(hex.substring(215, 239).split(":").reverse().join(""),16);
var bidPrice = parseInt(hex.substring(192, 215).split(":").reverse().join(""),16);
var price = String((+bidPrice+askPrice)/2);
var realprice = price.slice(0, price.length - 4) + "." + price.slice(price.length - 4);
if(+realprice <154 && +realprice >145) {
console.log(realprice);
}
}
});
How should I execute my code to get my data as fast as possible?
You're running JSON.parse(data) every iteration, that might take quite some time for a 500MB json file.
The solution would be to move it out of the loop and reuse the parsed object:
var obj = JSON.parse(data);
for (...

Render json string from controller to mvc view

My json string is coming as follows:
"[{\"StartTime\":\"09:00\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"09:30\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"10:00\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"10:30\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"},{\"StartTime\":\"11:30\",\"Dates\":\"05-28-2015\",\"Code\":\"DF\",\"LocationCode\":\"NY\"}]"
I need to parse this json string on view and show the data in a table.
I am new to json. Any help will be really appreciated. Thanks.
$("#divLoad").load("GetAvailableTimeSlots?strProvider=" + provider + "&strFrom=" + from, function (data) {
var newStr = data.replace('"[', '').replace(']"', '').replace('[', '').replace(']', '');
var dataArr = newStr.split('},{');
var jsonArr = new Array(dataArr.length);
for (var i = 0; i < dataArr.length; i++) {
dataArr[i] = '{' + dataArr[i] + '}';
var dataElem = dataArr[i].replace('{{', '{').replace('}}', '}');
var jsonElem = "'" + dataElem + "'";
jsonArr[i] = JSON.parse(jsonElem);
}
$(this).html(jsonArr);
});
If you are using jQuery, you can use the jQuery.parseJSON() method.
http://api.jquery.com/jquery.parsejson/
Just call JSON.parse(data) and manipulate the javascript object instead of performing error-prone string manipulation.
function (data) {
var locations = JSON.parse(data);
var table = $("<ul>");
for (var i = 0; i < locations.length; i++) {
var row = $("<li>").text(locations[i].StartTime + " " + locations[i].Dates + " " ...);
table.append(row);
}
$("#divLoad").empty().append(table); // $(this) won't work
}
This example is using an unordered list but you can easily replace this with table markup.
Here's what it looks like in Chrome dev tools with console.log(locations) after parsing:

How do I make a JSON object produce HTML on the page

Here is my JSON
var gal = [
{
"folder":"nu_images",
"pic":"gd_42.jpg",
"boxclass":"pirobox_gall",
"alt":"Rand Poster 1",
"title":"Rand Poster 1",
"thfolder":"th",
"thumbpic":"th_gd_42.jpg"
},
{
"folder":"nu_images",
"pic":"gd_13.jpg",
"boxclass":"pirobox_gall",
"alt":"Explosive Pixel Design",
"title":"Explosive Pixel Design",
"thfolder":"th",
"thumbpic":"th_gd_13.jpg"
}
];
and here is my for loop
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML = "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + ""
};
I am trying to make my JSON show all of the objects in HTML one after the other. I can get it to show the first one or whatever number I put into the array but I don't know how to make it generate a list of them.
Here is a link to my jsfiddle. Any help you can offer would be greatly appreciated.
http://jsfiddle.net/o7cuxyhb/10/
It's being generated here <p id="gallery"></p> just not correctly.
You're overwriting your html with every loop iteration:
document.getElementById("gallery").innerHTML = ...
^---
Perhaps you want something more like
document.getElementById("gallery").innerHTML += ...
^---
which will concatenation the original html contents with your new stuff.
And technically, you shouldn't be doing this in a loop. Changing .innerHTML like that causes the document to be reflowed/re-rendered each time you change .innerHTML, which gets very expensive when you do it in a loop. You should be building your html as a plain string, THEN adding it to the dom.
e.g.
var str = '';
foreach(...) {
str += 'new html here';
}
document.getElementById("gallery").innerHTML += str;
for (i = 0; i < gal.length; i++) {
document.getElementById("gallery").innerHTML += "" + "<img src=\"" + "http:\/\/galnova.com\/" + gal[i].folder + "\/" + "th\/" + gal[i].thumbpic + "\"" + "border=\"0\"" + "alt=\"" + gal[i].alt + "\"" + "title=\"" + gal[i].title + "\"\/>" + "" };
Add a += instead of an = after innerHTML
Try this:
function displayJson(jsonArray){
var container = document.getElementById("gallery");
for (var i=0; i<jsonArray.length; i++){
var newElement = document.createElement("a").innerHTML = jsonToHtml(jsonArray[i])
container.appendChild(newElement);
}
}
function jsonToHtml(jsonObj){
//Define your dom object here
var el = document.createElement("a").innerHTML = '' // you code here
...
return el;
}
displayJson(gal);

getRange(),setFormulas doesn't want to work

I have the following code and when I run it I get the right number of items in sheetFormulas (4), and the array values look correctly formed.
However, I get an error right after the sheetFormulas Browser.msgBox pops up, indicating the getRange().setFormulas line has an issue, but I can't see what it is.
function test(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var testingTarget = ss.getSheetByName("Testing");
var sheetFormulas = new Array();
for (l=0;l<10;l++) {
sheetRowCount = l + 2;
var monthlyTotalCompanyCosts = '=F' + sheetRowCount + '/$F$29*$I$14';
var monthlyTotalCompanyCostsPerEa = '=IFERROR(H' + sheetRowCount + '/C' + sheetRowCount + ')';
var monthlyMargin = '=D' + sheetRowCount + '-F' + sheetRowCount;
var monthlyMarginPctg = '=IFERROR(J' + sheetRowCount + '/D' + sheetRowCount + ')';
sheetFormulas.push(monthlyTotalCompanyCosts,monthlyTotalCompanyCostsPerEa,monthlyMargin,monthlyMarginPctg);
Browser.msgBox("sheetFormulas.length is: " + sheetFormulas.length);
Browser.msgBox("sheetFormulas is: " + sheetFormulas);
testingTarget.getRange(sheetRowCount,8,1,4).setFormulas(sheetFormulas);
sheetFormulas = [];
}
}
Any help is appreciated,
Phil
First, sheetFormulas has to be a 2D array. So try doing
/* Notice the [] around sheetFormulas */
testingTarget.getRange(sheetRowCount,8,1,4).setFormulas([sheetFormulas]);
If you still see other problems, then put your code inside a try{}catch{} block and print out the exception in the catch block.
I also suggest that you print out the formula using Logger.log() before setting it on the spreadsheet.

HTML5 SQLite Db questions

I've got a couple of questions regarding the Sqlite implementations for HTML5 website.
First of all, I'm trying to use the Synchronous Database calling openDatabaseSync method, but it doesn't seem to work... Someone used it already and could help me ?
Also, I'm struggling a bit trying to process the result return by my database query. I'd like my function to return an array of book, like this :
function searchByKeywordId(kw_id, element) {
cleanSearch();
element.innerHTML = "No result...";
var books = new Array();
db.transaction(function (tx) {
tx.executeSql("SELECT b.BK_TITLE,b.BK_URL, b.BK_THUMBNAIL_URL FROM KEYWORDS k INNER JOIN CATALOG_ITEMS c on k.KW_ID = c.KW_ID INNER JOIN BOOKS b on c.BK_ID = b.BK_ID WHERE k.KW_ID = ? GROUP BY b.BK_TITLE,b.BK_URL",[kw_id], function (tx, results) {
if (results.rows.length > 0) {
var html = "";
for (var i = 0; i < results.rows.length; i++) {
var bookId = results.rows.item(i).BK_ID;
var bookUrl = results.rows.item(i).BK_URL;
var bookTitle = results.rows.item(i).BK_TITLE;
var bookThumbnailUrl = results.rows.item(i).BK_THUMBNAIL_URL;
var book = new Book(bookId,bookTitle,bookUrl,bookThumbnailUrl);
books.push(book);
/*html += "<div class='x_container' id='calibre:book:" + bookId + "'>";
html += "<div class='cover'>";
html += "</div></div>";*/
html += "<a href='" + bookUrl + "' title=\"" + bookTitle + "\" target='_new'><img src='" + bookThumbnailUrl + "'></a> ";
}
//html += "</div>";
element.innerHTML = html;
}
});
});
return books; }
obviously, adding books within the callback methods doesn't work ... Do you see a way I could achieve that ? So that I would not have to write in the document from my database methods ...
Thanks !
On stackoverflow a question with javascript and "doesn't work" in it is usually a missing paren :) However I didn't find one in your code. I see some suspicious looking syntax around
,[kw_id], << did we really mean an array here, or are we de-referencing something...
In any case if that's not a mistake I would start by simplifying things, and not multipurposing your functions.
function searchByKeywordId(kw_id, element) {
cleanSearch();
var books = new Array();
db.transaction(function (tx) {
tx.executeSql("SELECT b.BK_TITLE,b.BK_URL, b.BK_THUMBNAIL_URL FROM KEYWORDS k INNER JOIN CATALOG_ITEMS c on k.KW_ID = c.KW_ID INNER JOIN BOOKS b on c.BK_ID = b.BK_ID WHERE k.KW_ID = ? GROUP BY b.BK_TITLE,b.BK_URL",[kw_id], function (tx, results) {
if (results.rows.length > 0) {
var html = "";
for (var i = 0; i < results.rows.length; i++) {
var bookId = results.rows.item(i).BK_ID;
var bookUrl = results.rows.item(i).BK_URL;
var bookTitle = results.rows.item(i).BK_TITLE;
var bookThumbnailUrl = results.rows.item(i).BK_THUMBNAIL_URL;
var book = new Book(bookId,bookTitle,bookUrl,bookThumbnailUrl);
books.push(book);
} // end for loop
} // end if block
} // end execute callback
); // end executeSql call
} // end transaction function argument
); // end db.transaction call
return books;
}
Then somewhere that you called this function do something like this:
var html="";
for (i=0; i<books.length; i++) {
html += "<a href='" + books[i].url + "' title=\"" + books[i].title + "\" target='_new'><img src='" + books[i].thumbnailUrl + "'></a> ";
}
if (html == "") {
html = "No result...";
}
element.innerHTML = html; // consider using jQuery here for browser compatability reasons
This will simplify debugging your code in firebug or whatever and be more readable. Later IF you need the performance, you can try to recombine and use the existing loop as an optimization... Premature optimization is usually a bad idea. Write clear code that works. Even if you know you should optimize it, get it working and then optimize it after it works (preferably after you've demonstrated that you do in fact need to optimize it).
http://www.flounder.com/optimization.htm