I'm using jQuery templating which is taking JSON data to create a table. This code is working fine. But when I try to create a function around this code and pass JSON data to it which I'm getting from an AJAX request, it shows the values in the console but not in the table. Working code with dummy data is:
var json = [{"class":12,"marks":"500","marks1":"200","marks2":"300"},{"class":11,"marks":"200","marks1":"300","marks2":"400"}]
$.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');
for(var i=0; i<json.length; i++){
$.tmpl('kList',json[i]).appendTo("#table1")
}
Here is the code where I'm warping the upper code in function and passing the JSON data as a parameter that shows the values in console when I print it with console.log(json) but not filling the table. The JSON parameter is having the same JSON data as in above code.
function dataTable(json){
console.log(json); // here json values are appearing in the console
$.template('kList','<tr title="${class}"><td>${marks}</td><td>${marks1}</td><td>${marks2}</td></tr>');
for(var i=0; i<json.length; i++){
$.tmpl('kList',json[i]).appendTo("#table1")
}
}
Please help me out because I don't know whats wrong in this code. Thanks in advance.
Your json parameter is a string. You should convert it to an object, using $.parseJSON(json).
Take a look at this for conversion detail.
Related
I am building an air app that needs to access data from Firebase Database using the REST API. I am able to get the data but I do not know how to get the information I need from that data.
Basically, I have an Android app and a Desktop app. The android app uploads/Modifies data and the Desktop app needs to access that data and send signals to the ESP8266 via a socket connection. I have a list of 'Lights' each light as a 'lightname', 'status' and 'pin'. I want to be able to loop through all the 'pin's.
When I try to get the data , I get this JSON:
{"-LAb_YKS9l7qQno25AY5":{"lightname":"light1","pin":"14","status":"on","timestamp":1524303808146},"-LAb_cRpsGpQfr7JbCfI":{"lightname":"light2","pin":"15","status":"on","timestamp":1524303830159},"-LAb_zbf2sYuyTtW_uEr":{"lightname":"blah","pin":"9","status":"on","timestamp":1524303921921},"-LAba68lzyG15n6anuSF":{"lightname":"dishl","pin":"7","status":"on","timestamp":1524303955946},"-LAdZW2JjQVGfLMc_sb4":{"lightname":"cxcxc","pin":"14","status":"on","timestamp":1524337092712}}
I want to loop through all the lights and access their 'pin' values.
Here is what i've tried:
for (var i:int = 0; i < e.target.data.length; i++)
{
trace(e.target.data[i]["status"]);
}
I get this error:
Property 0 not found on String and there is no default value.
Any help is greatly appreciated.
Because the e.target.data answer you get from Firebase is a String and first you need to JSON.parse(...) it to transform it into data. Then your data is not an Array, it is an Object. You loop through it as following:
// Parse the incoming data.
var aData:Object = JSON.parse(e.target.data);
// Loop through string keys of the data object.
for (var aKey:String in aData)
{
trace("");
trace(aKey);
// Assign entry reference to another local variable. This is not
// mandatory, but the following code is shorter and thus more readable.
var anEntry:Object = aData[aKey];
trace(anEntry['pin']);
trace(anEntry['status']);
trace(anEntry['lightname']);
}
If you have no use of key values, you might do it in a slightly different way:
// Parse the incoming data.
var aData:Object = JSON.parse(e.target.data);
// Loop through values of the data object while ignoring the keys.
for each (var anEntry:Object in aData)
{
trace("");
trace(anEntry['pin']);
trace(anEntry['status']);
trace(anEntry['lightname']);
}
I am trying to use the Kairos API for Facial Recognition in my air app. After i send the image, kairos returns the following JSON:
{"images":[{"transaction":{"status":"failure","topLeftX":106,"topLeftY":126,"gallery_name":"Faces","eyeDistance":42,"height":98,"width":98,"face_id":1,"quality":-1.53973,"message":"No match found"}}],"uploaded_image_url":"https:\/\/kairos-east-id-images.s3.amazonaws.com\/prod\/c6d565457\/recognize\/Faces\/d2b1142f2134232349ewer8acb825c87e909f299ab1_5a234XXXXXX.jpg?X-Amz-Content-Sha246=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=XXXXXXXXXXXXXX-east-1%2Fs3%2XXXX_request&X-Amz-Date=2017122rrtdfg158Z&X-Amz-SignedHeaders=host&X-Amz-Expires=XXXX&X-Amz-Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}
I need to access the values of "topLeftX", "topLeftY" and "message" but no matter what i try it doesn't seem to work. I have been searching around for about an hour. I have tried both native JSON parser and ascorelib JSON parser.
I tried the following:
var rawData:Object = JSON.decode(e.target.data);
for ( var object:Object in rawData ){
trace(object.transaction);
}
I get this error:
Property transaction not found on String and there is no default value.
I tried with different property names but I get the same error. I have tried sever other methods as well. Such as,
rawData["transaction"][0]["topLeftX"]
It doesnt work.
Any help is greatly appreciated.
I do not have a decode function on JSON. Just a JSON.parse and a JSON.stringify however what should work for you is this.
var jsonObj = JSON.parse(yourdata); // or JSON.decode if you AS version is older
for ( var i = 0 ; i < jsonObj.images.length ; i++ ){
trace(jsonObj.images[i].transaction.status);
}
I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John
Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model?
Maybe something like kendo.parseData(json, model), which will return array of objects?
I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:
function parse(model, json) {
// I initialize the model with the json data as a quick fix since
// setting the id field doesn't seem to work.
var parsed = new model(json);
var fields = Object.keys(model.fields);
for (var i=0; i<fields.length; i++) {
parsed.set(fields[i], json[fields[i]]);
}
return parsed;
}
Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.
I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.
kendo.data.DataSource.prototype.parse = function (data) {
return this.reader.data(data);
// Note that the original data will be modified. If that is not what you want, change to the following commented line
// return this.reader.data($.extend({}, data));
}
// ...
someGrid.dataSource.parse(myData);
If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.
this is my json format
({"message":{"success":true,"result":[{"lead_no":"LEA13","lastname":"Developer","firstname":"PHP","company":"Dummies","email":"nandhajj#gmail.com","id":"10x132"},{"lead_no":"LEA14","lastname":"Venu","firstname":"Yatagiri","company":"Rsalesarm","email":"veve#jajs.com","id":"10x133"},{"lead_no":"LEA4","lastname":"Jones","firstname":"Barbara","company":"Vtigercrm inc","email":"barbara_jones#company.com","id":"10x35"},{"lead_no":"LEA1","lastname":"Smith","firstname":"Mary","company":"Vtiger","email":"mary_smith#company.com","id":"10x32"}]}})
i am trying to retrieve the whole json result values using the following snippet
if (xmlHttp.readyState==4)
{
alert(xmlHttp.status);
if(xmlHttp.status==200)
{
alert("hi");
var jsondata=eval("("+xmlHttp.responseText+")") //retrieve result as an JavaScript object
jsonOutput=jsondata.result;
alert(jsonOutput);
InitializeLeadStorage()
}
}
my alert (hi ) is displayed but the alert(jsonOutput); is undefined , please help me if you could find any mistake
jsonOutput = jsondata.message.result;
result lives on message - it is not a top-level item in the JSON. With things like this, console.log() the JSON and you can check the path to the bit you want.
Also
your variable is global
there are better ways of parsing your JSON. If you don't care about old IEs, you can use the ECMA5 JSON.parse(), else use jQuery or another third-party utility for this