Render json string from controller to mvc view - json

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:

Related

Firebase "MD5" & BloddyCrytpo's dont match

I'm trying to do a check to see if the user has a local file. If the user does, I get bloodycrypto to make a md5 out of it. Then I compare the two values. One from the firebase file's metadata and the other from the byte array of the file digested. They never match. Does Firebase do something different when trying to generate the md5 of a file I upload?
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA)
trace("Local hash = " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("Network hash = " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
if (byteHash != storageMetaData.md5Hash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
Upon closer inspetion (thanks to Organis) firebase doesn't return a proper MD5. What is it? In my storage consol I don't see an md5 property, so is this autogenerated? The files were uploaded through my rest API based off phantom's guide.
Update: Following Organis' comment about the way Firebase handle's MD5s
var byteHash:ByteArray = new ByteArray();
byteHash.writeUTFBytes(MD5.hashBytes(fileBA));
var byteHashWithLength:ByteArray = new ByteArray();
byteHashWithLength.writeUTF(MD5.hashBytes(fileBA));
trace("Bytehash with length = " + Base64.encode(byteHashWithLength)); //ACAyMTMzYTdmYjczYTEzZDQ3ZDkzMTEyY2I1OWQyYTBmMg==
trace("Plain = " + Base64.encode(byteHash)); //OTNiODg1YWRmZTBkYTA4OWNkZjYzNDkwNGZkNTlmNzE=
trace("Storage md5 = " + storageMetaData.md5Hash); //UsoNl5sL1+aLiAhTOTBXyQ==
Trying to take the md5 I get and turn it into base64 results in consistent mismatching results. Is there an argument I am missing or applying incorrectly when I try to decode everything?
...So I would do something like
var storageHash:String = Base64.decode(storageMetaData.md5Hash).toString();
to follow your example right?
Try this code below to get your storageMetaData.md5Hash correctly decoded from Base64 :
Let me know result of trace("storage hash : " + storageHash); to check if you're getting an (expected) sequence of 32 hex values.
private function handleMetaSuccess(e:StorageReferenceEvent):void
{
trace("Meta succes for reference:" + this.name);
storageMetaData = e.metadata;
trace("reading file.");
fileBA = new ByteArray();
var fs:FileStream = new FileStream();
fs.open(Definitions.CACHE_DIRECTORY.resolvePath(name + ".jpg"), FileMode.READ)
fs.readBytes(fileBA);
fs.close();
var byteHash:String = MD5.hashBytes(fileBA); //Local hash
var ba_storageHash:ByteArray = new ByteArray();
ba_storageHash = Base64.decode(storageMetaData.md5Hash); //update ByteArray
var storageHash:String = bytesToHexString(ba_storageHash); //Hex values of bytes shown as String
trace("Network hash : " + storageMetaData.md5Hash); //bo7XPotC+T5wmAcpagnXBw==
trace("Local hash : " + byteHash); //93b885adfe0da089cdf634904fd59f71
trace("storage hash : " + storageHash); //what is result??
if (byteHash != storageHash)
{
trace("Not equal. Getting file."); //Always happens
getFile();
}
else
{
loadFile();
}
}
// # Byte values (Hex) shown as (returned) String type
private function bytesToHexString(input:ByteArray) : String
{
var strOut:String = ""; var strRead:String = "";
input.position = 0;
var intBASize:uint = input.length;
for (var i:int = 0; i < intBASize; i++)
{
strRead = input.readUnsignedByte().toString(16);
if(strRead.length < 2) { strRead = "0" + strRead; } //# do padding
strOut += strRead ;
}
return strOut.toLowerCase(); //strOut.toUpperCase();
}

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 (...

how to use json object in html ActionLlink helper method with query string?

I am using below anchor tag,in using json object.How to write it using html helper method.
success: function (data) {
var str = "";
for (i = 0; i < data.length; i++) {
str += "<a href=/Home/GetArtistRelatedData?str=" + data[i].ArtistName + " target='_blank' style='color:gold;'>" + data[i].ArtistName + "</a><br/>";
}
$("#mm").append(str);
}

Confused to read 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]);

How to access name of key in dynamically created json in action script 3

I have a json object coming from my java code as string :
{
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
}
on decoding it as
myObj : Object = JSON.decode(result);
Now how do I access key names like ABC, OMG, HELLO...??
Try this will help you.
When you want properties in object use for-in loop or you want value use foreach statement.
var obj:Object = {
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
};
var jsonText:String = JSON.stringify(obj);
var jsonObj:Object = JSON.parse(jsonText);
for(var key:String in jsonObj){
Alert.show("Key is"+key + " value is "+ jsonObj[key]);
}
Your case exactly
var myObj:Object = JSON.decode(result);
for(var key:String in myObj){
Alert.show("Key is"+key + " value is "+ myObj[key]);
}