Serialize as object using json.net - javascript

I want certain properties to be serialized as 'objects' and not strings. E.g.
{"onClickHandler": OnClickHandler,
"onMouseOut": OnMouseOutHandler}
The class def is like this:
public class handlers {
public string OnClickHandler;
public string OnMouseOutHandler;
}
Currently it comes out as:
handlers: {"onClickHandler": "OnClickHandler",
"onMouseOut": "OnMouseOutHandler"}
As you can guess, these are client side event handlers and correspond to javascript functions defined elsewhere. By emitting them within quotes, they are not interpreted as functions but as literal strings.
Edit:
Taking a cue out of Dave's answer, figured out a way:
first a little bit of scrubbing:
for (var handler in this.handlers) {
if(window[this.handlers[handler]])
this.handlers[handler] = window[this.handlers[handler]];
};
and then call jQuery bind normally
$elem.bind(this.handlers);
Accepting Dave's answer as that is closest.

JSON does not support representing functions. JSON consists of arrays of values, and objects (containing variables). Values in JSON can only be strings, numbers, objects or arrays (see the linked page for nice grammar diagram).
What you're after is javascript code, not a JSON object. If you're wanting to emit a reference to a function defined elsewhere, you may have to (shudder) use eval to execute it.

As someone else mentioned, that wouldn't be valid JSON anyway (which precludes you from using JSON.parse(), among other potential drawbacks).
If your event handler functions are defined in the global window scope, you could call them like this:
// This is equivalent to defining window.clickEventHandler or
// window['clickEventHandler'] as a function variable.
function clickEventHander() {
// Magic.
}
// Valid JSON, using strings to reference the handler's name.
var json = '{"onClickHandler": "clickEventHandler"}'
// You might be using eval() or a framework for this currently.
var handlerMappings = JSON.parse(json);
window[handlerMappings.onClickHandler]();

Related

Modify JSON.stringify() for specific components

I have a React component state that holds many different classes that needs to be stringify()'d. Most of the components need to be specially treated before they can be put into the JSON object. I believe that using the replacer() and if statements to check the type and then modify the output would be too cumbersome. Short of creating a custom parsing system, is there a way to customize the stringify() in what it parses?
The idea would be to have a custom function (toString() for example) in each class that when the parser reaches the class, instead of going through the key-value pairs, would call the function and append it to the JSON object.
From JSON.stringify description
If the value has a toJSON() method, it's responsible to define what data will be serialized.
Usage
JSON.stringify({ toJSON() {return {a: 'eureka'}}})

JavaScript: how to pass object value from one function to another

I am using code lines like the following in order to fetch data from an intranet website:
util.setProp(obj, "firstNameOld", $(msg).find('#fname_a').text());
Now I have another function in the same file where I want to use the above again, resp. the value of that object - currently I am hard-coding this ('Test') for test purposes:
util.setProp(obj, "firstNameNew", 'Test');
How can I pass the value from the firstNameOld object in one function to the firstNameNew object in another function ? If a solution with global variables is better here than this would work as well.
Many thanks for any help with this, Tim.
I've never used the framework that includes util But I imagine that if there is a setProp() then there has to be a getProp() or something similar.
If so, you could do something like
util.setProp(obj, "firstNameNew", util.getProp(obj, "firstNameOld"));
This also relies on the assumption that you want to copy from two properties in the same object.
If not, then pass the desired source object in the getProp() call.
My guess is that functions (or properties) are called "firstNameOld" and "firstNameNew", so the first time you get it from selector, second time you want to do the same.
Try to use the local variable like that:
var text = $(msg).find('#fname_a').text();
//
util.setProp(obj, "firstNameOld", text);
//
util.setProp(obj, "firstNameNew", text);

Creating a struct of arrays in Javascript

I have a variable called jsonAllSignOffs that is created by a .NET JSON service and sent to the client. It is essentially a struct containing various arrays. The values of these arrays are arranged such that if you took the nth element of each array, all together that would be the collected properties of the nth Sign Off. Obviously a list of Sign Off objects containing these properties would be better, but unfortunately this is a legacy application and changing it's architecture in this manner is out of scope.
What I'm trying to do is create a variable called jsonUserSignOffs that is essentially a subset of jsonAllSignOffs with all the same properties. However jsonAllSignOffs is not a type that I can instantiate. I figured declaring a variable and assuming the properties by assigning into them would "build" the object, but apparently that's not the case.
var jsonUserSignOffs;
jsonUserSignOffs.isAuthor = jsonAllSignOffs.isAuthor; //error jsonUserSignOffs is undefined
Since javascript doesn't support classes and is pretty lax with variables I figured the only way to create a struct like jsonAllSignOffs was to declare the variable and assign values to it's properties. I know these properties are not defined anywhere, but I thought assigning values to them would instantiate them at the same time. I come from a C# background where I would use a class. Javascript is less familiar to me, and I'm unclear on how to proceed.
Try this
var jsonUserSignOffs = {}; //creates an empty object using object literal notation
jsonUserSignOffs.isAuthor = jsonAllSignOffs.isAuthor;
OR:
var jsonUserSignOffs = {
isAuthor: jsonAllSignOffs.isAuthor
};

Javascript objects with JSON

Im sure this must have been asked before but I can't find an example on SO.
I have a JSON string that starts out life as something like this:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC"},"changed":{"PC":"AC"}}
The string needs to be changed on user input such that "selection" records all the input the user has click on and "changed" is the last thing the user clicks on.
So I have a function that reads the JSON string from a textarea, modifies it dependant on what the user has selected (node and value) and then writes it back to the text area for debugging.
function changeJSON(node, value) {
json = JSON.parse($('#json').val());
json.selection[node] = value;
delete json.changed;
json.changed = {node:value};
$('#json').val(JSON.stringify(json));
}
"selection" works nicely but "changed" updates to the literal variable name I pass it (in this case node) I.e. if I called the function with changeJSON("BC","HC") the JSON string becomes:
{"model":"14","imgsize":"890","selection":{"SC":"BC","PC":"AC","BC":"HC"},"changed":{"node":"HC"}}
I understand what javascript is trying to do but I want the changed element to be what my variable contains i.e.
,"changed":{"BC","HC"}
and not
,"changed":{"node","HC"}
I'd love someone to tell me what I am doing wrong!?
EDIT
Solved - see below for Quentin explanation as to why and my answer for the code changes necessary - hope it helps others.
I don't think this is the same question, mine is why the literal variable name is used rather than the contents of the variable
The question referenced explains how to resolve the issue, but since you are asking for an explanation.
A variable name is a JavaScript identifier.
A property name in object literal syntax is also a JavaScript identifier (although you can use a string literal instead).
Since an identifier cannot be both a variable and a property name at the same time, you cannot use variables for property names in object literal syntax.
You have to, as described in the referenced question, create the object and then use the variable in square bracket notation.
The solution, as Quentin suggested is to create th object first i.e.
delete json.changed;
json.changed = {};
json.changed[node] = value;

Programatically output variable and object names as literal text strings

I'd really like to track variables without switching between Firebug console windows or clicking around so much, so I want to draw a runtime viewer of variable names and their corresponding values that will display on the page of the app I am building.
I'd like to two functions, show(variableName) and freeze(variableName). They will output both the variable's value and the name of the variable or object as a literal string which will serve as the text label in the viewer. freeze(variableName) is the same as show(variableName) except with a setTimeOut timer for tracking loops.
I'm sure I'm missing something basic, but I haven't found out a way to get the string that comprises the name of a value programmatically so I can use it as a label. I guess I could create the table with hardcoded labels prior to runtime and just populate it with values at runtime, but I really want to generate the table dynamically so it only has those variables I specifically want to show or freeze. Simple functions:
foo1 = "Rock";
show(foo1);
foo2 = "Paper";
show(foo2);
foo3 = "Scissors";
show(foo3);
should output this via getElementById('viewer-table'):
<table>\<tr><td>foo1</td><td>Rock</td></tr><tr><td>foo2</td><td>Paper</td></tr><tr><td>foo3</td><td>Scissors</td></tr></table>
I've tried this solution:
How to convert variable name to string in JavaScript?
and eval() but it's not working for me...I dunno, shouldn't this be easy? Getting frustrated...
Thanks,
motorhobo
I am not sure you can actually get the "name" of the variable that is being passed into a function for two reasons:
1) The variable is just an identifier. In fact, you could have multiple identifiers reference the exact same object. You are (generally) passing that reference, not any actual object.
2) The show/freeze function is going to stomp on the identifier name, either through named arguments in the function declaration or by referencing them through the arguments array.
I was trying to think if there was some clever way to use the arguments.callee or the stack property on an exception in Firefox... but I can't see anything that would expose the arguments as you desire.
What I would recommend is to simply add the name of the variable and its value to a simple object, and call one of the various jsDump methods (I prefer the one in QUnit):
function show(o) {
document.getElementById("viewer-table").innerHTML = QUnit.jsDump(o);
}
// actually use the method
show({"foo1":foo1});
There's no easy way to solve this as the called function simply doesn't know the original name of the variable. You couldn't solve this with reflection even (esp. in javascript) so you'll have to pass the name of the variable to the function too. To follow the link you posted:
function show(varObject)
{
for(name in varObject)
{
alert(name + ": " + varObject[name]);
// save both name and reference to the variable to a local "to observe array"
}
}
And call it with
var test = "xxx";
show({'test' : test});
Within the for loop you could add easy variable to a monitor array and update your gui in fixed time intervalls (you can't be notifed when a signle variable changes it's value. You need some kind of global monitor/observer which exactly you're trying to create).

Categories