When I use the System.Web.Script.Serialization.JavaScriptSerializer.Serialize method, I get back valid JSON code.
This is usually perfect, but sometimes I want to get back the result as a Javascript object, not JSON. The Serialize method has an overload that takes a SerializationFormat parameter. That looks perfect... but it is marked as internal!
How can I get out a string of Javascript from the Serializer?
Take a look at the JScript DLL Eval object's JScriptEvaluate method (http://msdn.microsoft.com/en-us/library/microsoft.jscript.eval.jscriptevaluate.aspx):
using Microsoft.JScript;
var MyJSObject = Eval.JScriptEvaluate("{a:'Property1',b:'Property2'}", Engine);
Related
Scenario: Java servlet running on glassfish 4.1/jdk1.8.45. There is a javascript function being read from Database and executed on server side using javax.script.*. When trying to debug this function, it is desired to output some json objects on server log.It is printing [Object object] instead of the actual JSON.Tried using JSON.stringify(), it gives[undefined].
Is there a way to print the actual contents on the json object in this scenario?
Thanks.
JSON.stringify works only javascript objects. It does not work on Java objects. Please make sure that you're calling JSON.stringify on a JavaScript object.
If you do need to make JSON string on a java object, you can use Object.bindProperties extension (https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Object.bindProperties) to bind properties of the Java object to a script object and then call JSON.stringify on the same.
Sample (test) code is here -> http://hg.openjdk.java.net/jdk9/dev/nashorn/file/0de67a63e2c7/test/script/nosecurity/treeapi/utils.js
This script is used to convert a Nashorn AST tree object [a Java object] as friendly JSON object.
If you want to use JSON.stringify and it gives undefined, does it mean JSON is undefined or just the function?
If so, it may be that Nashorn doesn't have it in the box. Maybe try and add it as a polyfill: you can have a look here or here.
If you are dealing with strings in the Nashorn scripting engine then there is a probability they are Java strings rather than javascript strings. The fix is to convert your Java strings to Javascript strings.
// this string does not work with stringify()
var javaString = someMethodReturningAJavaString();
var jsString = new String(javaString);
// now stringify() works:
var myJson = JSON.stringify({'key': jsString});
If typeof(new String(javaString)) returns object rather than string then use new String(javaString).valueOf(). For some values this seems to be the only solution with Mozilla's Rhino js engine.
If you have numbers then you might need to wrap java objects in the the new Number() constructors.
For details on the Nashorn engine have a look at https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html
Came across this snippet
var someDataJSON = jQuery.parseJSON(JSON.stringify(someData));
According to MDN the inner "method converts a JavaScript value to a JSON string"; then the outer method "Takes a well-formed JSON string and returns the resulting JavaScript value" per jQuery
If you start with a JS value & end up with a JS value, is this a pointless operation?
Usually that is a trick used to get a by-value copy of an object in javascript. (Since all objects are passed by reference). You can find a more in-depth answer on how to accomplish this, if you're curious, in this stackoverflow post
If someDataJSON is a flat JSON object, this way you get a copy of that object. Since, there is no direct method to copy a javascript object "by value" [and not "by reference"], this trick can be used.
var copyJSONObj = JSON.parse(JSON.stringify(JSONObj))
So, there is some point after all.
For example, I'm trying to isolate the first 5 characters of window.location.
var ltype, string = 'string';
console.log(window.location); // file:///C:/for example
console.log(typeof window.location); // [OBJECT]
lType=window.location.substr(0,5); // 'not a function' (quite so)
string=window.location;
lType=string.substr(0,5); // fails similarly
Q1: Can I somehow 'bind' substr() to window.location?
I can see that string=window.location replicates a reference and not
a value, so
Q2: How can a separate, discrete copy of a complex structure such as an object or an array be created [without using JSON.stringify() or JSON.parse() - which is what I am presently resorting to]?
try
string = window.location.href.toString();
instead of
string=window.location;
Because window.location will return object not a string.
window.location is an object, so you can't use string functions on it - as you've noticed. In order to get the actual location as a string (to perform string operations on it), you'll need to convert it to a string somehow.
window.location.href is a property provided by the object itself.
window.location.toString() is a method on all JavaScript objects, overridden here.
However, beware of the XY problem. It looks to me like you're trying to retrieve the protocol (the http: bit) of the URI. There's a property for that too - window.location.protocol.
lType = window.location.protocol;
You should use that - it's more robust (consider https:// or, worse, ftp://...).
I want to call a method in flex from javascript side,
so that I can retrieve javascript object which contains data in flex.
now I'm trying like
var result:Object = new Object()
var keyset:Array = data.getKeySet();
for (var i:int = 0 ; i < keyset.length ; i++) {
result[keyset[i]] = data.get(keyset[i]);
}
return result;
but it do not work. how can I make it right?
p.s. I know it is fundamental question, but I couldn't find anything even though I googled for an hour. So please help!
To communicate between Flash/Flex and JS on the page, use the ExternalInterface class. You can't directly pass objects, but you can convert your object into a serialisable/string. Here's how you'd call a function called 'myFunc' and set it two arguments, a string and a number:
ExternalInterface.call('myFunc',1,'aString');
After the function name, which must always be a string, there is a ...rest parameter. Simply enough, this means you can send any number of arguments to the function, separating them with commas (we do two here).
If you used AS2 at any point in the past you may know the 'eval' function, this was inherited from (and is thus still used by) JS - it analyses a string and attempts to parse it into JavaScript, using this you can literally send Javascript code instead of a func/args:
ExternalInterface.call('alert("Hello!")');
If you want two-way communication, use the ExternalInterface.addCallBack function to register a function as callable from JS.
In case of errors when doing this, you may need to adjust your embed code: "In the object tag for the SWF file in the containing HTML page, set the following parameter:
param name="allowScriptAccess" value="always"
I believe you cannot call a method in AS3 from JS directly (and vice-versa). There should be an interface for it though, where one can call the other. If i remember correctly, you should use the ExternalInterface API.
Also, you can't pass Flex objects to JS (and vice-versa) also. Try building a generic object that is serializable to JSON and use that serialized data in passing data to each other. The receiving party can parse it back to use the data. In this example, the code passed a string from JS to AS3.
In your case, the Flex function would:
build an object
stuff it with data
serialize it into a JSON string
return the string to the caller
Then when JS calls the function:
JS receives the string
Use JSON.parse() to reconstruct the JSON string into a JS object
use the object
I'm attempting to convert a JSON object to a "normal" object using the following...
var slaobj = eval('('+s+')');
s being the JSON. however, it doesnt seem to work (It's `.length' is coming back as undefined). What am I doing wrong?
It's `.length' is coming back as undefined
It won't necessarily have a length property, unless it's an array or some other object that has one. For example:
var json = '{"foo": "Value of foo"}';
var obj = eval('(' + json + ')');
alert(obj.foo); // alerts "value of foo"
alert(obj.length); // alerts "undefined", there's no `length` in `obj`
Live example
Off-topic: Using eval to deserialize JSON text can be a security problem, unless you can unambiguously trust the source of the JSON text (for instance, it's your own server and you're connecting via SSL), because eval doesn't parse JSON, it parses and runs JavaScript code. (Adding the parentheses doesn't really help.) You can get alternatives to using eval from Douglas Crockford's Github page (he's the inventor of JSON). Last I checked, there are three alternatives there, two of which don't use eval at all; see the README at the bottom of the page for details.
Objects don't all have ".length" properties. An object literal like:
{ 'foo': 100, 'bar': 'Abraham Lincoln' }
describes an object that has no ".length" property.
JavaScript Array objects have ".length" properties because of the way the language runtime works. But a plain object in JavaScript only has such a property if you put it there.
How are you retrieving the object?
I would say there has to be something else wrong - are you sure the 's' JSON object was returned correctly?
JSON.org
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval('(' + myJSONtext + ')');
Update: Ah, I see, that's what the parentheses are for. Rats. Deleted the first part.
But this remains valid:
Don't use eval!
eval() is a dangerous function, which
executes the code it's passed with the
privileges of the caller. If you run
eval() with a string that could be
affected by a malicious party, you may
end up running malicious code on the
user's machine with the permissions of
your webpage / extension. More
importantly, third party code can see
the scope in which eval() was invoked,
which can lead to possible attacks in
ways of which the similar Function is
not susceptible.
Source: Mozilla JavaScript Reference: eval()
http://www.jsonlint.com/ this site has good JSON string validation which you should have at your disposal all the times. It's good to validate the JSON string when its really big.
Also do not user the eval() to get the JSON object. Visit http://www.json.org/ it has really nice guide lines check it.
There are many JavaScript libraries today which offers JSON API. I will suggest you to user one of it for safety.
http://api.jquery.com/jQuery.getJSON/
http://developer.yahoo.com/yui/json/
http://dojotoolkit.org/reference-guide/dojo/_base/json.html