Defining recrussive JSON Object notation - json

Whats wrong in below JSON Object definition
I am trying to create a new JSON Object like below.
So that my idea is to access COMPANYSETUP.HourSetup.initiate();
Not sure the error ?
COMPANYSETUP = {
initiated : false,
companyId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
} },
HourSetup = {
initiated : false,
hourId : "",
initiate : function() {
if(!initiated){
// TO DO
initiated = true;
}
}
}
};

Assuming you want a javascript object and not JSON, which disallows functions,
HourSetup =
Should be changed to:
HourSetup :
Also, as JonoW points out, your single line comments are including some of your code as the code is formatted in the post.

There's a "=" that shouldn't be there. Change it to ":"

JSON is a form of JavaScript deliberately restricted for safety. It cannot include dangerous code elements like function expressions.
It should work OK in plain eval()ed JavaScript, but it's not JSON.

Related

Obfuscation for Asp MVC using SmartAssembly or CryptoObfuscator

I have a question in using CryptoObfuscator or RedGate SmartAssembly to obfuscate Asp Mvc Assemblies :
It seems when you use one of these tools to obfuscate assemblies, then they will rename properties of classes, right?
so I think because of this operation we will lose access to some of the values in JSON format that would comes from server during serialization ( I mean that because of renaming the properties we cant parse JSON object in JS correctly)
If this is true, so how can we prevent loosing parseJSON operation in JS?
Let me include more details :
consider this class structure
public class MyClass
{
public string FName{get;set;}
. . .
}
//SampleController :
public JsonResult GetJson()
{
return Json(new MyClass{FName = "Alex"});
}
Now in ClientSide :
$.ajax({
url: "/Sample/GetJson",
context: document.body
}).success(function(data) {
//this is my problem : can I access to FName or Not?
var fname = jQuery.parseJSON(data).FName;
});
Basically Obfuscators DO NOT change return value's Property's names.
But if some obfuscator does so... you can Simply accomplish this by using following in your ajax call:
$.ajax({
url: "/Sample/GetJson",
dataType: "json"
success: function(data) {
var transformedData = {fname:arguments[0], somethingElse:arguments[1]};
//or
var fname = arguments[0];
//do the rest here...
}
});
You can also use [DoNotObfuscate] attribute in "smart assembly"
By using this, you can prevent json results from being obfuscated at all (on server side).
Also there should be some (other/same) strategies for other obfuscators.
I personally use CryptoObfuscator and it has some options to prevent (what/where) ever you'd like from being obfuscated.

Collection+JSON with AngularJS

I'm working on a project where various tables of data will be displayed with AngularJS. The data will be in the Collection+JSON format, as shown below. I found this library https://github.com/Medycation/angular-collection-json, I'm not sure how to make it work. Below is an example of the data.
angular.module('app', ['cj']);
var $injector = angular.injector();
var cj = $injector.get('cj');
cj("cjapi1.php").then(function(cjProvider){
console.log(collection.items());
});
I tried the above. In the console it says I need to register cjProvider as a provider. Any help with how to set this up properly would be appreciated. Thanks.
{
“collection”:
{
“version”: “0.1”,
“href” : “https://example.com/companies”
“items” : [
{
“href” : “https://example.com/companies/123”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 1”}
}
},
{
“href” : “https://example.com/companies/1234”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 2”}
}
},
]
}
Please configure your cjProvider while configuring your module. Check the below code template for the reference to configure cjProvider.
angular.module('app', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});
Please make sure that you have configured your transformUrl just shown above.
Your base url must be configured in cjProvider and while hitting any url ang getting data you should transform your request like here you are requesting cjapi1.php. so your baseurl must be append before that like your_base_url + 'cjapi1.php' this will be done for all requesting api. So cjProvider will take care that and will return api path and in .then(responce) you will get your responce which is collection.
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
Are you trying to configure or get the contents of the collection from php call?
Looks like a typo to me but try this to get collection:
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
...and this for configuration of your provider:
angular.module('agile', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});

How can I prevent ExtJS 4.2.1 from processing the totalProperty on a PUT request?

We are using ExtJS 4.2.1 and Spring MVC / Data-Rest. Anyway, the data-rest will return the following structure on a successful GET request:
{
content: [ ... objects .... ],
links: [ ... list of rel links ... ],
page: {
size: 25,
totalElements: 4,
totalPages: 1,
number: 1
}
}
So, in my proxies, I have set the totalProperty to page.totalElements. Works great.
However, when we send a PUT request, the natural (and correct, I believe) response is to send a 204 NO CONTENT. Now, if our totalProperty were set to something like total (not page.xxx) then it's fine. But ExtJS is trying to parse the page.totalElements and returning an exception because page is null.
So how can I tell ExtJS to ignore the totalProperty on a PUT request?
Ha. Looks like I found a work-around. Not sure if I like it but it works. I changed my controller as such:
return new ResponseEntity<>("OK", HttpStatus.OK);
Where as before, it was:
return new ResponseEntity(HttpStatus.OK);
ExtJS seems to not mind that. Strange.
#cbmeeks, I had a similar issue in Ext.JS 4.1.3, and I posted the fix here.
/**
* Fix for Json reader when the HTTP response is Status Code: 204 No Content and
* at least one of the pair root/totalProperty is not a direct property of the returned json
* http://www.sencha.com/forum/showthread.php?127585
* #author rgralhoz
*/
Ext.data.reader.Json.override({
createAccessor: (function () {
var re = /[\[\.]/;
return function (expr) {
if (Ext.isEmpty(expr)) {
return Ext.emptyFn;
}
if (Ext.isFunction(expr)) {
return expr;
}
if (this.useSimpleAccessors !== true) {
var i = String(expr).search(re);
if (i >= 0) {
return Ext.functionFactory('obj',
'return obj' + (i > 0 ?
'.hasOwnProperty("' +
expr.substring(0, i) +
'")? obj.' + expr + ' : null' :
expr));
}
}
return function (obj) {
return obj[expr];
};
};
}())
});
Disclaimer:
Please add this code to a fixes.js file in your project, to override Ext.Js' function. Please notice that:
The fix for 4.2.1 may be the same or similar
Once you override their function, when you upgrade Ext.Js, make sure they haven't change it, otherwise you'll loose updates on their code.

working with JSON data, trying to parse nested data

I just working with JSON data and am playing around with jQuery and Ajax requests. Pretty basic stuff, but here's my problem.
I have a basic data set which I was using for time tracking. I know how to parse the simple JSON data like this:
{
"end" : "1/18/2011",
"start" : "1/18/2011",
"task" : "Code Review",
},
It's the more complicated stuff I'm trying to parse like this where I'm trying to pull the "time" data out.
{
"end" : "1/17/2011",
"start" : "1/17/2011",
"task" : "Exclusive Brands",
"time" : {
"analysis" : 4,
"documentation" : 3,
"meetings" : 2
}
This is the code for the script I've been using to parse the simple data:
$(function() {
$('.load').click(function(){
$.getJSON("data.js",function(data){
$.each(data.timesheet, function(i,data){
var div_data ="<div class='box'>"+data.start+" "+data.task+"</div>";
$(div_data).appendTo("#time-tracking");
});
}
);
return false;
});
});
My question is what's the format to parse the time data, or what's the best way to parse the information nested inside the time element?
Any help will be greatly appreciated.
A JSON string will be parsed into an object. When parsed, the time is the key of one object. You could retrieve the value of this object through the dot operator (.).
data = JSON.parse('{"end":"1/17/2011", "start":"1/17/2011", "task":"Exclusive Brands", "time": {"analysis":4, "documentation":3, "meetings":2 } }')
// => obj
data.time.analysis
// => 4
In your case similarly you could use the data.time.meetings to access your data from remote server.
Unless I am terribly mistaken, since jquery already converted data into a javascript for you, you should be able to access time as if it was a javascript object like so:
var analysis = data.time.analysis;
var documentation = data.time.documentation;
var meetings = data.time.meetings;
etc...

How do I get rid of recursive AJAX requests for a childless node?

Problem:
According to the author, jsTree Documentation:
When opening a closed node (that has no loaded children) an AJAX request is made.
How do I configure jsTree to get rid of these AJAX data requests made for each empty/childless node? I want my empty nodes remain empty (or childless)!
Given (simplified):
JSON data container (data.json)
{
"data" : "Root node with no children",
"children" : []
}
jsTree configuration
{
"json_data" : {
"ajax" : {
"url" : "data.json",
"type" : "GET",
"dataType" : "json",
"dataFilter" : function (data, type) {
//some filtering function
}
}
},
"plugin" : ["json_data"]
}
Mark the state of the leaf node as "leaf". That should fix it.
I have had this problem setting the attribute state="closed" on childless nodes for XML trees. Removing the state attribute solves the issue.
I had a similar problem a couple of weeks ago. I had a function call in the "url" field, which ultimately led to java code that made a JSON string based on a SQL query. So when I clicked on a childless closed node, the function was called again, resulting in an endless tree.
the way I solved this was:
"json_data" : {
"ajax" : {
"url" : "getAreaTree?treeType=Areas&ownerPhone=<%=webSessionObject.getUserPhoneNum()%>",
"data" : function (n) {
return { id : n.attr ? n.attr("id") : 0 };
}
}
},
The result of the function defined in "data" will be added as a parameter to the "url" function. Then I can check whether the parameter was 0 (initial load) or 1 (the id of my root) or something else.
If this doesn't work for you, maybe you could try something like this:
.bind("before.jstree",function(event,data){
if(data.func === "create"){
var foo = true;
data.inst._get_node(null, true).each(function () {
if(this.id!=rootId && this.id!=0){
foo = false;
})
if(!foo){
event.stopImmediatePropagation();
return false;
}
}
})
I'm not exactly sure this works though. "before.jstree" fires before all events. I'm checking whether the function about to fire is "create", and if it is I check the id of the selected node. If it's something else than my root's id or 0 (initial load) I stop the create function.
I use a similar structure for a different situation, so something like this should work. It could be that the "create" event is not what you should be binding to though. You can change it to
.bind("before.jstree",function(event,data){
console.log(data.func)
if(data.func === "create"){
To see which functions are called.
Just skip the children attribute. Obviously your node has no children, but you specify the attribute? Simply skip it, the node will be rendered as a leaf node and no further requests will be made.
I've been struggling with this problem too. I got the main idea from jsTree - loading subnodes via ajax on demand
The basic problem is that when we click a child node that is not set to leaf, a new AJAX request is generated with the URL we set in the tree configuration. The trick seen in the above link is to provide a function instead of a static URL string. My jstree is used to display a directory structure on the server, so I can arrange to dynamically add to the URL for sub-directories. If you assign a function to the url property of the ajax property in your jstree configuration, the function receives the node you clicked as an argument. My nodes display the names of directories or files so I can use the text() function to get the raw directory name. There seems to be some space in front of the name returned in this way, so I used a String trim() function and then encodeURIComponent to give me something I can use in a URL.
If -1 is passed to the url function, then you're at the root and you can safely use your base URL. Now, this only works for the first level of the hierarchy. I've got a bit more work to do, adding the full path to the metadata of the node or something like that, but this idea might put you on the right track. It looks as if it's not exactly a bug but by design. You have to make sure a request triggered by a subnode sends a suitable URL to the server.
Here's the url property I've assigned to the ajax object in my jstree configuration:
"url": function (node) {
var subDirectory = "",
url = "";
if (node === -1)
{
url = "/tree_service/tree/format/json?path=exercises";
}
else
{
subDirectory = encodeURIComponent(node.text().trim());
url = "/tree_service/tree/format/json?path=exercises/" + subDirectory;
}
return url;
}
My plan is to build the URL cumulatively by polling the node for its full path, then adding the node's name as above to create the final URL. Pseudo code:
//haven't figured out how to add the path to the node and then retrieve it
path = node.metadata.path;
path = encodeURIComponent(path);
subDirectory = encodeURIComponent(node.text().trim());
url = path + "/" + subDirectory;
UPDATE
See my answer here how to get the metadata of jsTree. about getting the metadata from the node using node.data().path