I have following code where i combine some variables to create path to the another existing object and his attribute.
Problem is that i alway get only string, so i would like to "convert" it into the object.
// SET CUSTOM CONTENT FOR COLUMN IF CONTACT ATTR IS EXISTS
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var nameForConcat;
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
nameForConcat = null;
fieldName = null;
objectName = null;
objectName = value.field;
fieldName = concatField.fieldName;
console.log("FIELD NAME IS");
console.log(JSON.stringify(fieldName));
console.log("OBJECT NAME IS");
console.log(objectName);
nameForConcat = objectName+"."+fieldName;
console.log("CONCATED NAME IS");
console.log(nameForConcat);
console.log("OBJECT ADDRESS IS FOLLOWING");
console.log("responseData."+nameForConcat);
pathToReturn = "responseData."+nameForConcat;
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}
Returned value should be value of another and global existing json object. But now is it always string.
It means:
responseData.SomeObject.surname
How can i solve it please?
Many thanks for any help.
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
objectName = value.field;
fieldName = concatField.fieldName;
pathToReturn = responseData[objectName][fieldName];
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}
Related
My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});
Take Parse Javascript SDK 1.6.4 for example,
from line 179:
_CoreManager2['default'].setCloudController({
run: function run(name, data, options) {
var RESTController = _CoreManager2['default'].getRESTController();
var payload = (0, _encode2['default'])(data, true);
var requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
requestOptions.sessionToken = options.sessionToken;
}
var request = RESTController.request('POST', 'functions/' + name, payload, requestOptions);
return request.then(function (res) {
var decoded = (0, _decode2['default'])(res);
if (decoded && decoded.hasOwnProperty('result')) {
return _ParsePromise2['default'].as(decoded.result);
}
return _ParsePromise2['default'].error(new _ParseError2['default'](_ParseError2['default'].INVALID_JSON, 'The server returned an invalid response.'));
})._thenRunCallbacks(options);
}
});
The _decode2['default'] uses fromJSON for Parse Object from line 4144:
key: 'fromJSON',
value: function fromJSON(json) {
if (!json.className) {
throw new Error('Cannot create an object without a className');
}
var constructor = classMap[json.className];
var o = constructor ? new constructor() : new ParseObject(json.className);
var otherAttributes = {};
for (var attr in json) {
if (attr !== 'className' && attr !== '__type') {
otherAttributes[attr] = json[attr];
}
}
o._finishFetch(otherAttributes);
if (json.objectId) {
o._setExisted(true);
}
return o;
}
I passed a full Parse object in my cloud code run success callback, but this decoding behavior purges my returning Parse object into a object reference.
Why do we want to have this?
Is there a option to get full object instead of a reference?
What I want is to get an updated object to update my view on success.
I have created a function in controller in which I have created three sessions and passed the values. I need to pass the values to some variables in jquery file to use it in a function.
Here is the controller function
public string GetAssociatedCompSetsForGroup(string groupID, string ScreenName)
{
Session["WorkBookID"] = Session["workbookId"];
Session["groupID"] = groupID;
Session["ScreenName"] = ScreenName;
IList<int> compSetsIds = serviceKMALocator.InvokeService<IList<int>>(x => x.GetAssociatedCompSetsForGroup(Convert.ToInt32(groupID), ScreenName));
string ids = string.Empty;
foreach (int id in compSetsIds)
{
ids = ids + id.ToString() + Constant.SemiColon;
}
if (!string.IsNullOrEmpty(ids))
{
ids = ids.Substring(0, ids.Length - 1);
}
ViewBag.CompSetIds = ids;
Session[Constant.CompSetIds] = compSetsIds;
return ids;
}
and the values of three sessions i have created in the controller should be passed to the variables in the following code and i have tried something like this.
var GroupID = '<%=Session("groupID")%>';
var WorkBookID = '<%=Session("WorkBookID")%>';
var ScreenName = '<%=Session("ScreenName")>';
if (GroupID != null && WorkBookID != null && ScreenName != null)
{
$.post(compsetForGroup, { groupID: GroupID, ScreenName: ScreenName }, function (jsonData) {
if (jsonData) {
function ajaxCall(no) { .....
Please help me with the correct format. Thankyou in advance.
in your JavaScript Codes:
var WorkBookID = "#Session[0]";
var groupID= "#Session[1]";
var ScreenName = "#Session[2]";
that sessions 0 to 2 is equivalence to the value of WorkBookID ,groupID,ScreenName sessions Respectively.
Try this:
var GroupID = '<%=Session["groupID"]%>';
var WorkBookID = '<%=Session["WorkBookID"]%>';
var ScreenName = '<%=Session["ScreenName"]>';
if (GroupID && WorkBookID && ScreenName)
{
This is how I've done it
var OppoId = '#(OMSSession.SessionProperties.SelectedOpportunityId)';
I am having some trouble trying to pass string objects to a function. In the query string of the url I pass fields which is a comma delimited string containing the attributes of interest.
I put the names of those attributes in the fields array. However now I am having trouble passing that information to a function.
In the code below the query.pluck('id', 'name') works, the query.pick( fieldString ) does not.
I am stuck on this one, how can I pass the attribute names in the fields array to the function so it will work?
Please advice.
var log = require('logule').init(module,'query');
var url = require('url');
module.exports = {
build : function(req, entity, callback) {
var isCollection;
isCollection = req.params.id? false: true;
var query = req.rethink.table(entity);
parsedUrl = url.parse(req.url, true);
console.log(isCollection);
if (parsedUrl.query.fields) {
var fields = parsedUrl.query.fields.split(',');
var total = fields.length;
fieldString = fields[0];
for (var i = 1; i < total; i++) {
fieldString += ', ' + fields[i];
}
if (isCollection) {
var query = query.pluck('id', 'name');
} else {
var query = query.get(req.params.id).pick( fieldString );
}
}
return callback(null, query);
}
}
You don't need to put fields in a string, just use
var query = query.get(req.params.id).pick.apply(this,fields);
You need to use the "apply" function with the function name, and an array of parameters (fields in your case)
var query = query.get(req.params.id).apply('pick', fields);
I have been looking for an answer to this all afternoon and i cant seem to find the best way to accomplish what i need to.
My JSON string (returned from a web service) has circular references in it (#ref) which point to $id in the string. Now i know that if use jquery parseJSON it creates the javascript object and i can access properties a la myObject.MyPropertyName. However, when i get to a #ref, i am unsure how to get the object that ID points to (which i assume is already created as a result of the de-serialization...
Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
$.ajax({
type: "POST",
url: "/Task.asmx/GetTask",
data: "{'id':'" + '27' + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
_Data = $.parseJSON(msg.d ? msg.d : msg);
_this.Company = _Data[0].t_Program.t_Company;
_this.Program = _Data[0].t_Program;
_this.Task = _Data[0];
},
complete: function () {
}
});
The area in question is _Data[0].t_Program because it does not return an object but rather returns
_Data[0].t_Program
{...}
$ref: "12"
I dont exactly know the best way to get the object with $id "12". Based on the posts below it seems i should loop through the existing object, but i was hoping there was a jquery function that did that...
Many Thanks!
No, jQuery is not natively capable of resolving circular references in objects converted from JSON.
The only library for that which I know is Dojo's dojox.json.ref module.
But, your server application serializes that JSON somehow. Don't tell me that the solution it uses does not offer a deserialisation algorithm!
As my friend Alan, the author of the Xerox Courier (RPC over the net) library, used to say to me, "there are no pointers on the wire."
In other words, it is impossible for a JSON representation of a data structure to be circular. (But a circular structure can be flattened into a non-circular JSON structure.) As the JSON site says:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
No pointers!
So the entire JSON will have been turned into Javascript Objects and/or Arrays after the jQuery parseJSON operation completes.
If the original stucture's ref_id values were used as the property names in the JSON / Javascript object, then they'll all be there.
The real issue is that you need to understand how your server serialized its data structure into the JSON data structure. Look in your server-side code to determine that.
Then use Javascript to de-serialize the JSON structure back into the best Javascript structure to fit your needs.
Re: Should i be iterating though the object and all its child objects until i find it, or is there an easier way?
The easier way would be to go through the Javascript structure once, and build up an additional "indexing" object whose properties are the #ref_id and the values are the original structure/value.
Sample:
var jsonCyclicReferenceFixed = JsonRecursive.parse(jsonWithRefAndId);
(function(){
function type(value){
var t = typeof(value);
if( t == "object" && value instanceof Array) {
return "array";
}
if( t == "object" && value && "$id" in value && "$values" in value) {
return "array";
}
return t;
}
function TypeConverterFactory(){
var converters = {};
var defaultConverter = {
fromJson: function(value){ return value; },
toJson: function(value){ return value; },
};
this.create = function(type){
var converter = converters[type];
if(!converter) return defaultConverter;
return converter;
};
this.register = function(type, converter){
converters[type] = converter;
converter.valueConverter = this.valueConverter;
};
}
function ObjectConverter(){
this.fromJson = function(obj){
if( obj == null ) return null;
if( "$ref" in obj ){
var reference = this.dictionary[obj.$ref];
return reference;
}
if("$id" in obj){
this.dictionary[obj.$id] = obj;
delete obj.$id;
}
for(var prop in obj){
obj[prop] = this.valueConverter.convertFromJson(obj[prop]);
}
return obj;
}
this.toJson = function(obj){
var id = 0;
if(~(id = this.dictionary.indexOf(obj))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(obj).toString() };
for(var prop in obj){
convertedObj[prop] = this.valueConverter.convertToJson(obj[prop]);
}
return convertedObj;
}
}
function ArrayConverter(){
var self = this;
this.fromJson = function(arr){
if( arr == null ) return null;
if("$id" in arr){
var values = arr.$values.map(function(item){
return self.valueConverter.convertFromJson(item);
});
this.dictionary[arr.$id] = values;
delete arr.$id;
return values;
}
return arr;
}
this.toJson = function(arr){
var id = 0;
if(~(id = this.dictionary.indexOf(arr))){
return { "$ref" : (id + 1).toString() };
}
var convertedObj = { "$id" : this.dictionary.push(arr).toString() };
convertedObj.$values = arr.map(function(arrItem){
return self.valueConverter.convertToJson(arrItem);
});
return convertedObj;
}
}
function ValueConverter(){
this.typeConverterFactory = new TypeConverterFactory();
this.typeConverterFactory.valueConverter = this;
this.typeConverterFactory.register("array", new ArrayConverter);
this.typeConverterFactory.register("object", new ObjectConverter);
this.dictionary = {};
this.convertToJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.toJson(valor);
}
this.convertFromJson = function(valor){
var converter = this.typeConverterFactory.create(type(valor));
converter.dictionary = this.dictionary;
return converter.fromJson(valor);
}
}
function JsonRecursive(){
this.valueConverter = new ValueConverter();
}
JsonRecursive.prototype.convert = function(obj){
this.valueConverter.dictionary = [];
var converted = this.valueConverter.convertToJson(obj);
return converted;
}
JsonRecursive.prototype.parse = function(string){
this.valueConverter.dictionary = {};
var referenced = JSON.parse(string);
return this.valueConverter.convertFromJson(referenced);
}
JsonRecursive.prototype.stringify = function(obj){
var converted = this.convert(obj);
var params = [].slice.call(arguments, 1);
return JSON.stringify.apply(JSON, [converted].concat(params));
}
if(window){
if( window.define ){
//to AMD (require.js)
window.define(function(){
return new JsonRecursive();
});
}else{
//basic exposition
window.jsonRecursive = new JsonRecursive();
}
return;
}
if(global){
// export to node.js
module.exports = new JsonRecursive();
}
}());
Sample:
// a object recursive
// var parent = {};
// var child = {};
// parent.child = child;
// child.parent = parent;
//
//results in this recursive json
var json = '{"$id":"0","name":"Parent","child":{"$id":"1","name":"Child","parent":{"$ref":"0"}}}'
//Parsing a Recursive Json to Object with references
var obj = jsonRecursive.parse(json);
// to see results try console.log( obj );
alert(obj.name);
alert(obj.child.name);